java lambda表达式之collect(Collectors.toList())

今天写代码时,写了下面的代码:

fieldList.stream().filter(xxxx).map(selfDefineMethod())

因为我不需要用stream返回的list,所以后面没有加.collect(Collectors.toList()),结果不及预期,好像这句没有执行一样;后来才发现原因是:

 *
 * 

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 {@link Stream#filter(Predicate)}), and a * terminal operation (which produces a result or side-effect, such * as {@link Stream#count()} or {@link Stream#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必须后面加上所谓的terminal operation,类似于count()、forEach()、collect()等操作之后,才会消费原始数据流。

你可能感兴趣的:(java lambda表达式之collect(Collectors.toList()))