JDK8、JDK17运行效果不同,jdk17不会打印元素,他认为即使不打印也不会影响最后count的结果
List<String> l = Arrays.asList("A", "B", "C", "D");
long count = l.stream().peek(System.out::println).count()
JDK17的解释
/**
* Returns the count of elements in this stream. This is a special case of
* a <a href="package-summary.html#Reduction">reduction</a> and is
* equivalent to:
* <pre>{@code
* return mapToLong(e -> 1L).sum();
* }</pre>
*
* <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>.
*
* @apiNote
* An implementation may choose to not execute the stream pipeline (either
* sequentially or in parallel) if it is capable of computing the count
* directly from the stream source. In such cases no source elements will
* be traversed and no intermediate operations will be evaluated.
* Behavioral parameters with side-effects, which are strongly discouraged
* except for harmless cases such as debugging, may be affected. For
* example, consider the following stream:
* <pre>{@code
* List<String> l = Arrays.asList("A", "B", "C", "D");
* long count = l.stream().peek(System.out::println).count();
* }</pre>
* The number of elements covered by the stream source, a {@code List}, is
* known and the intermediate operation, {@code peek}, does not inject into
* or remove elements from the stream (as may be the case for
* {@code flatMap} or {@code filter} operations). Thus the count is the
* size of the {@code List} and there is no need to execute the pipeline
* and, as a side-effect, print out the list elements.
*
* @return the count of elements in this stream
*/
long count();