搜索
您的当前位置:首页正文

重走Java基础之Streams(二)

来源:知库网

Processing Order

Example:

List<Integer> integerList = Arrays.asList(0, 1, 2, 3, 42); 

// sequential 
long howManyOddNumbers = integerList.stream()
                                      .filter(e -> (e % 2) == 1).count(); 

System.out.println(howManyOddNumbers); // Output: 2

Parallel(并行)模式允许在多个核上使用多个线程,但不能保证处理元素的顺序。

如果在顺序的Stream上调用多个方法,则不必调用每个方法。 例如,如果一个Stream被过滤,并且元素的数量减少到一,则不会发生对诸如sort的方法的后续调用。 这可以提高顺序的Stream的性能 - 这是一个并行的Stream不可能实现的优化。

Example:

// parallel
long howManyOddNumbersParallel = integerList.parallelStream()
                                              .filter(e -> (e % 2) == 1).count();

System.out.println(howManyOddNumbersParallel); // Output: 2

Differences from Containers (or Collections)

虽然一些操作可以在Containers和Streams上执行,但它们最终用于不同的目的并支持不同的操作。 容器更注重元素的存储方式以及如何有效地访问这些元素。 另一方面,Stream不提供对其元素的直接访问和操纵; 它更专用于作为集体实体的对象组并且作为整体对该实体执行操作。 Stream和Collection是用于这些不同目的的单独的高级抽象。

Consuming Streams

IntStream.range(1, 10).filter(a -> a % 2 == 0).peek(System.out::println);

这是一个具有有效终端操作的 Stream 序列,因此产生一个输出。
你也可以使用forEach而不是peek:

IntStream.range(1, 10).filter(a -> a % 2 == 0).forEach(System.out::println); 

Output:

2
4
6
8

在执行终端操作之后, Stream 被执行消耗,不能被重复使用。

一般来说,Stream的操作如下图所示:

NOTE: 即使没有终端操作,也始终执行参数检查

try {
      IntStream.range(1, 10).filter(null);
  } catch (NullPointerException e) {
      System.out.println("We got a NullPointerException as null was passed as an argument to filter()");
  }

Output:

We got a NullPointerException as null was passed as an argument to filter()

Creating a Frequency Map

Stream.of("apple", "orange", "banana", "apple")
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
        .entrySet()
        .forEach(System.out::println);

This would produce the following output:

banana=1
orange=1
apple=2

Infinite Streams 无限流

这个例子生成一个所有自然数的Stream,从数字1开始。Stream的每个连续项比上一个高一个。 通过调用这个Stream的limit方法,只有Stream的前5个项被考虑和打印。

// Generate infinite stream - 1, 2, 3, 4, 5, 6, 7, ...
IntStream naturalNumbers = IntStream.iterate(1, x -> x + 1);

// Print out only the first 5 terms
naturalNumbers.limit(5).forEach(System.out::println);

Output:

1
2
3
4
5

Collect Elements of a Stream into a Collection 将流的元素收集到集合中

Collect with and

System.out.println(Arrays
    .asList("apple", "banana", "pear", "kiwi", "orange")
    .stream()
    .filter(s -> s.contains("a"))
    .collect(Collectors.toList())
);
// prints: [apple, banana, pear, orange]

Explicit(显式) control over the implementation of or

// syntax with method reference
System.out.println(strings
        .stream()
        .filter(s -> s != null && s.length() <= 3)
        .collect(Collectors.toCollection(ArrayList::new))
);

// syntax with lambda
System.out.println(strings
        .stream()
        .filter(s -> s != null && s.length() <= 3)
        .collect(Collectors.toCollection(() -> new LinkedHashSet<>()))
);

Parallel Stream

当你想同时并发执行Stream操作时,你可以使用这些方法。

List<String> data = Arrays.asList("One", "Two", "Three", "Four", "Five");
Stream<String> aParallelStream = data.stream().parallel();

Or:

Stream<String> aParallelStream = data.parallelStream();

要执行为并行流定义的操作,请调用终端运算符:

aParallelStream.forEach(System.out::println);

(A possible) output from the parallel Stream:

Three
Four
One
Two
Five

性能影响

在涉及网络的情况下,并行的 Stream可以降低应用的整体性能,因为所有并行的 Stream对于网络使用公共的fork-join线程池。

另一方面,在许多其他情况下,根据当前运行的CPU中可用内核的数量,并行的 Stream可以显着提高性能。

本文完!


Top