I am in the progress of learning through Java 8 lambda expressions and would like to ask about the following piece of Java code relating to the peek
method in the function interface that I have come across.
On execution of the program on IDE, it gives no output. I was expecting it would give 2, 4, 6
.
import java.util.Arrays;
import java.util.List;
public class Test_Q3 {
public Test_Q3() {
}
public static void main(String[] args) {
List<Integer> values = Arrays.asList(1, 2, 3);
values.stream()
.map(n -> n * 2)
.peek(System.out::print)
.count();
}
}
I assume you are running this under Java 9? You are not altering the
SIZED
property of the stream, so there is no need to execute eithermap
orpeek
at all.In other words all you care is about
count
as the final result, but in the meanwhile you do not alter the initial size of theList
in any way (viafilter
for example ordistinct
) This is an optimization done in the Streams.Btw, even if you add a dummy filter this will show what you expect:
Here's some relevant quotes from the Javadoc of Stream interface:
And more specifically from the Javadoc of count() method:
These quotes only appear on the Javadoc of Java 9, so it must be a new optimization.