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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…