Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...