JAVA Stream用法

Stream(流)在JAVA已经不是一个新词了。很早以前咱们就接触过JAVA中的输入输出流(IO Stream),它是对数据输入输出操做的抽象封装。JAVA8中提出一个集合流的抽象工具(java.util.stream,简称Stream),用于集合内元素的计算,更确切的说是过滤和统计操做。java

Stream建立

Stream不是一种真实的数据源(不存在数据结构),因此咱们没有办法直接来建立它,Stream只能依赖其余数据源来转换成咱们的抽象操做。Stream自己是不存在,只是咱们抽象出来的一个抽象操做,通过各类操做以后,Stream还须要转换成真实的数据源。数组

常见建立方式以下:数据结构

  • Collection

parallelStream()app

stream()ide

  • Stream.of(...)
  • Arrays.stream(...)
  • Stream.generate(...)
  • Stream.iterate(seek, unaryOperator)
  • BufferedReader

lines()工具

其实最终都是依赖StreamSupport类来完成Stream建立的。this

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.spa

Stream操做由零个或多个中间操做(intermediate operation)和一个结束操做(terminal operation)两部分组成。只有执行结束操做时,Stream定义的中间操做才会依次执行,这就是Stream的延迟特性。orm

中间操做

  • 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操做提升了数据处理效率、开发效率。
相关文章
相关标签/搜索