why java streams skip method force to execute other operations

Viewed 64

In below code, secnario-1, map method never executed to produce count of my list. I understand this is lazy loading. But in the second scenario, why map method got executed, just to fetch the count of my list? JVM just could skip 3 elements can bring the count without executing the map method.

public static void main(String[] args) {
        List<String> list = Arrays.asList("abc1", "abc2", "abc3", "xyz", "xyz2");
        // scenario-1
        long count1 = list.stream().map(a -> {
            System.out.print("Map-");
            return a.substring(0, 2);
        }).count();
        System.out.println(count1);

         // scenario-2
        long count2 = list.stream().skip(3).map(a -> {
            System.out.print("Map-");
            return a.substring(0, 2);
        }).count();
        System.out.println(count2);
    }
}
1 Answers

I understand this is lazy loading

You don't understand it correctly. It is not "lazy loading", but a short-circuit operation. Executing map does not alter the fact the underlying spliterator is still SIZED, even after map:

boolean isSized =
   list.stream().map(x->x).spliterator().hasCharacteristics(Spliterator.SIZED);
System.out.println(isSized); // true

unlike when you add skip:

boolean isSized =
   list.stream().skip(3).map(x->x).spliterator().hasCharacteristics(Spliterator.SIZED);
System.out.println(isSized); // false
Related