Java 8 Stream

Java 8 Stream

Stream 是 Java 8 新特性,可对 Stream 中元素进行函数式编程操作,例如 map-reduce。Stream 表示一个序列,其中的元素支持串行或并行的聚合方法。

1
2
3
4
int sum = widgets.stream()
.filter(b -> b.getColor() == RED)
.mapToInt(b -> b.getWeight())
.sum();

什么是 Stream?

Stream(流)是一个来自数据源的元素队列并支持聚合操作

  • 元素是特定类型的对象,形成一个队列。 Java中的Stream并不会存储元素,而是按需计算。
  • 数据源 流的来源。 可以是集合,数组,I/O channel, 产生器generator 等。
  • 聚合操作 类似SQL语句一样的操作, 比如filter, map, reduce, find, match, sorted等。
  • 和以前的Collection操作不同, Stream操作还有两个基础的特征:
    • Pipelining: 中间操作都会返回流对象本身。 这样多个操作可以串联成一个管道, 如同流式风格(fluent style)。 这样做可以对操作进行优化, 比如延迟执行(laziness)和短路(short-circuiting)。
    • 内部迭代: 以前对集合遍历都是通过Iterator或者For-Each的方式, 显式的在集合外部进行迭代, 这叫做外部迭代。 Stream提供了内部迭代的方式, 通过访问者模式(Visitor)实现。

如何获得 Stream ?

  1. Collection to Stream

Collection 接口的实现类,可以通过 Collection.stream() 或 Collection.parallelStream() 方法返回 Stream 对象.

1
2
3
4
public static <T> Stream<T> fromCollection(Collection<T> collection,boolean parallel) {
return (collection ==null || collection.isEmpty())?
Stream.empty() : parallel ? collection.parallelStream() :collection.stream();
}
  1. Array to Stream

可以通过静态方法 Arrays.stream(T[] array) 或 Stream.of(T… values) 将数组转为 Stream.

1
2
3
4
public static <T> Stream<T> fromArray(T[] array,boolean parallel) {
return (array ==null || array.length == 0)?
Stream.empty() : parallel? Arrays.stream(array).parallel():Arrays.stream(array);
}