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