在进入正题之前,我们需要先引入Java 8中Stream类型的两个很重要的操作:
中间和终结操作(Intermediate and Terminal Operation)
Stream类型有两种类型的方法:
中间操作(Intermediate Operation)
终结操作(Terminal Operation)
官方文档给出的描述为[不想看字母的请直接跳过]:
Stream operations are divided into intermediate and terminal operations, and are combined to form stream pipelines. A stream pipeline consists of a source (such as a Collection, an array, a generator function, or an I/O channel); followed by zero or more intermediate operations such as Stream.filter or Stream.map; and a terminal operation such as Stream.forEach or Stream.reduce.
Intermediate operationsreturn a new stream. They are always lazy; executing an intermediate operation such as filter() does not actually perform any filtering, but instead creates a newstream that, when traversed, contains the elements of the initial stream that match the given predicate. Traversal of the pipeline source does not begin until the terminal operation of the pipeline is executed.
Terminal operations, such as Stream.forEach or IntStream.sum, may traverse the stream to produce a result or a side-effect. After the terminal operation is performed, the stream pipeline is considered consumed, and can no longer be used; if you need to traverse the same data source again, you must return to the data source to get a new stream. In almost all cases, terminal operations are eager, completing their traversal of the data source and processing of the pipeline before returning. Only the terminal operations iterator() and spliterator() are not; these are provided as an &#