Search code examples
javajava-stream

Why doesn't the count() terminal operation print the intermediate steps?


As simple as:

import java.util.stream.*;

public class MyClass {
  public static void main(String args[]) {
    Long x = Stream.of(1, 2, 3).map(i -> {
      System.out.println(i);
      return i + 4;
    }).count();

    System.out.println(x); // prints '3'
  }
}

The count() here is used in order to trigger the intermediate operations which include System.out.println(i), but nothing gets printed from inside map(). Why is that?


Solution

  • Streams are lazy and smart. Since your terminal operation is count, which does not care of individual elements, but only of their number, map isn't called.
    Replace count with something that would need to calculate individual elements, like sum - and map will be called.

    Long x = Stream.of(1, 2, 3).map(i -> {
                System.out.println(i);
                return i + 4;
            })
            .mapToLong(Long::valueOf)
            .sum(); // prints 1 2 3
    
            System.out.println(x); // prints 18
    

    Also a person in comments rightfully reminds you side effects.