In other words, is the following line guranteed to print num
lines?
int num = list.stream().peek(System.out::println).count();
This question was triggered by a discussion in the comments of https://stackoverflow.com/a/41346586/2513200
I vaguely remember a discussion that optimizations that avoid iteration might be legal, but didn't find anything conclusive during a quick search.
The JavaDocs for Stream.count contain this statement:
This is a special case of a reduction and is equivalent to:
return mapToLong(e -> 1L).sum();
but I'm not sure whether this provides any guarantees if the stream can somehow determine the result in a short-circuiting way.
The counting() method of the Java 8 Collectors class returns a Collector accepting elements of type T that counts the number of input elements.
Stream count() method in Java with examples long count() returns the count of elements in the stream. This is a special case of a reduction (A reduction operation takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation).
A Stream is considered consumed once a terminal operation is executed. However, even multiple intermediate operations are not supposed to be executed for the same Stream instance, as stated in the Stream javadoc: A stream should be operated on (invoking an intermediate or terminal stream operation) only once.
count() The Java Stream count() method is a terminal operation which starts the internal iteration of the elements in the Stream , and counts the elements.
Nope, it's not. It will not do it in Java 9 due to optimized count()
implementation (if stream size is known in advance, it will skip iteration).
See JDK-8067969 for more details. The documentation in JDK-9 was updated accordingly:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With