Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Stream.count() guranteed to visit each element?

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.

like image 704
Hulk Avatar asked Dec 27 '16 14:12

Hulk


People also ask

What does count () do in Java?

The counting() method of the Java 8 Collectors class returns a Collector accepting elements of type T that counts the number of input elements.

How do you count elements in a stream?

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).

Can a stream be consumed more than once?

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.

Is count a terminal operation on stream?

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.


1 Answers

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.

like image 68
Tagir Valeev Avatar answered Sep 27 '22 19:09

Tagir Valeev