Stream(流)在JAVA已经不是一个新词了。很早之前我们就接触过JAVA中的输入输出流(IO Stream),它是对数据输入输出操作的抽象封装。JAVA8中提出一个集合流的抽象工具(java.util.stream,简称Stream),用于集合内元素的计算,更确切的说是过滤和统计操作。
Stream创建
Stream不是一种真实的数据源(不存在数据结构),所以我们没有办法直接来创建它,Stream只能依赖其他数据源来转换成我们的抽象操作。Stream本身是不存在,只是我们抽象出来的一个抽象操作,经过各种操作之后,Stream还需要转换成真实的数据源。
常见创建方式如下:
Collection
parallelStream()
stream()
Stream.of(...)
Arrays.stream(...)
Stream.generate(...)
Stream.iterate(seek, unaryOperator)
BufferedReader
lines()
其实最终都是依赖StreamSupport类来完成Stream创建的。
Stream操作
To perform a computation, stream operations are composed into a stream pipeline. A stream pipeline consists of a source (which might be an array, a collection, a generator function, an I/O channel, etc), zero or more intermediate operations (which transform a stream into another stream, such as filter(Predicate)), and a terminal operation (which produces a result or side-effect, such as count() or forEach(Consumer)). Streams are lazy; computation on the source data is only performed when the terminal operation is initiated, and source elements are consumed only as needed.
Stream操作由零个或多个中间操作(intermediate operation)和一个结束操作(terminal operation)两部分组成。只有执行结束操作时,Stream定义的中间操作才会依次执行,这就是Stream的延迟特性。
中间操作
filter
Returns a stream consisting of the elements of this stream that match the given predicate.
返回一个符合条件的Stream。
map
Returns a stream consisting of the results of applying the given function to the elements of this stream.
返回由新元素组成的Stream。
mapToInt、mapToLong、mapToDouble
返回int、long、double基本类型对应的Stream。
flatMap
Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Each mapped stream is closed after its contents have been placed into this stream. (If a mapped stream is null an empty stream is used, instead.)
简单的说,就是一个或多个流合并成一个新流。
flatMapToInt、flatMapToLong、flatMapToDouble
返回对应的IntStream、LongStream、DoubleStream流。
distinct
返回去重的Stream。
sorted
返回一个排序的Stream。
peek
主要用来查看流中元素的数据状态。
limit
返回前n个元素数据组成的Stream。属于短路操作
skip
返回第n个元素后面数据组成的Stream。
结束操作
forEach
循环操作Stream中数据。
forEachOrdered
暗元素顺序执行循环操作。
toArray
返回流中元素对应的数组对象。
reduce
聚合操作,用来做统计。
collect
聚合操作,封装目标数据。
min、max、count
聚合操作,最小值,最大值,总数量。
anyMatch
短路操作,有一个符合条件返回true。
allMatch
所有数据都符合条件返回true。
noneMatch
所有数据都不符合条件返回true。
findFirst
短路操作,获取第一个元素。
findAny
短路操作,获取任一元素。
总结
Stream每个操作都是依赖Lambda表达式或方法引用。
Stream操作是一种声明式的数据处理方式。
Stream操作提高了数据处理效率、开发效率。