Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 854
microwth Avatar asked Sep 07 '25 03:09

microwth


2 Answers

The javadoc for count() has note that:

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.

like image 137
DuncG Avatar answered Sep 10 '25 10:09

DuncG


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.

like image 45
ILya Cyclone Avatar answered Sep 10 '25 12:09

ILya Cyclone