Search code examples
javalambdajava-8java-9peek

Stream.peek() method in Java 8 vs Java 9


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();
    }
}

Solution

  • 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 either map or peek 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 the List in any way (via filter for example or distinct) This is an optimization done in the Streams.

    Btw, even if you add a dummy filter this will show what you expect:

    values.stream ()
          .map(n -> n*2)
          .peek(System.out::print)
          .filter(x -> true)
          .count();