Package java.util.stream Description

Classes to support functional-style operations on streams of elements, such as map-reduce transformations on collections. For example:

public static void main(String[] args) {
    int sum = widgets.stream()
            .filter(b -> b.getColor() == RED)
            .mapToInt(b -> b.getWeight())

Here we use widgets, a Collection, as a source for a stream, and then perform a filter-map-reduce on the stream to obtain the sum of the weights of the red widgets. (Summation is an example of a reduction operation.)

Streams differ from collections in several ways:

  • No storage. A stream is not a data structure that stores elements; instead, it conveys elements from a source such as a data structure, an array, a generator function, or an I/O channel, through a pipeline of computational operations.


  • Functional in nature. An operation on a stream produces a result, but does not modify its source. For example, filtering a Stream obtained from a collection produces a result, but does not modify its source. For example, filtering elements from the source collection.


  • Laziness-seeking. Many stream operations, such as filtering, mapping, or duplicate removal, can be implemented lazily, exposing opportunities for optimization. For example, “find the first String with three consecutive vowels” need not examine all the input strings. Stream operations. Intermediate operations area always lazy.

延遲尋求。許多流操作(例如過濾,映射或重複刪除)可以延遲實施,從而提升優化的效能。例如,”String使用三個連續的元音查找第一個”不需要檢查所有輸入字符串。 流操作分為中間(產生Stream)操作和最終(產生值或副作用)操作。中間操作總是延遲的。

  • Possibly unbounded. While collections have a finite size, streams need not. Short-circuiting operations such as limit(n) or findFirst() can allow computations on infinite streams to complete in finite time.


  • Consumable. The elements of a stream are only visited once during the life of a stream. Like an Iterator, a new stream must be generated to revisit the same elements of the source.



  • 不是數據結構(Not a data structure)
  • 專為lambdas設計(Designed for lambdas)
  • 不支持索引訪問(Do not support indexed access)
  • 可以輕鬆輸出為數組或列表(Can easily be outputted as arrays or lists)
  • 支持延遲訪問(Lazy access supported)
  • 可並行化(Parallelizable)

Ref: Java 8流-Java流示例-HowToDoInJava


  1. Stream Creation
  2. Stream Pipelines
  3. Stream Operations
  4. Lazy Invocation
  5. Parallelism