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操做提升了數據處理效率、開發效率。
相關文章
相關標籤/搜索