streams - Stream Creation

本文深入探讨Java 8中的Stream API,展示如何从集合创建流,进行元素映射及消费操作,包括示例代码和运行结果,适用于希望提升Java编程技能的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

An important aspect of steam is that they are lazy which means they are only evaluated when ablolutely necessary.

There are three types of operations: creating streams, modifying elements of a stream (intermediate operation), and consuming stream elements (terminal operations).

// streams/CollectionToStream.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

import java.util.*;
import java.util.stream.*;

public class CollectionToStream {
  public static void main(String[] args) {
    List<Bubble> bubbles = Arrays.asList(new Bubble(1), new Bubble(2), new Bubble(3));
    System.out.println("bubbles.stream():" + bubbles.stream());
    System.out.println(
        "bubbles.stream().mapToInt(b -> b.i):" + bubbles.stream().mapToInt(b -> b.i));
    System.out.println(bubbles.stream().mapToInt(b -> b.i).sum()); // stream(), interface Collection default method since 1.8

    Set<String> w = new HashSet<>(Arrays.asList("It's a wonderful day for pie!".split(" ")));
    w.stream().map(x -> x + " ").forEach(System.out::print); // Lambda Expression + method reference since 1.8
    System.out.println();

    Map<String, Double> m = new HashMap<>();
    m.put("pi", 3.14159);
    m.put("e", 2.718);
    m.put("phi", 1.618);
    System.out.println("m:" + m);
    System.out.println("m.entrySet():" + m.entrySet());
    m.entrySet().stream().map(e -> e.getKey() + ": " + e.getValue()).forEach(System.out::println);
  }
}
/*My Output:
bubbles.stream():java.util.stream.ReferencePipeline$Head@7852e922
bubbles.stream().mapToInt(b -> b.i):java.util.stream.ReferencePipeline$4@53d8d10a
6
a pie! It's for wonderful day
m:{phi=1.618, e=2.718, pi=3.14159}
m.entrySet():[phi=1.618, e=2.718, pi=3.14159]
phi: 1.618
e: 2.718
pi: 3.14159
*/

references:

1. On Java 8 - Bruce Eckel

2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/streams/CollectionToStream.java

3. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/streams/Bubble.java

4. https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#stream--

5. https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#mapToInt-java.util.function.ToIntFunction-

6. https://howtodoinjava.com/java-8-tutorial/

7. https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#entrySet--

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值