I was learning Stream.limit()
says:
Returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length.
This can be understood from:
Stream.of(1,2,3,4,5,6,7,8)
.limit(3)
.forEach(i -> {
System.out.print(i + ",");
}); //prints: 1,2,3,
However when used with other stream methods, it has an effect of processing elements in batch:
Stream.of(1,2,3,4,5,6,7)
.filter(i -> {
System.out.println("Filtering " + i + ": " + (i%2 == 0));
return i%2 == 0;
})
.map(i-> {
System.out.println("Mapping " + i + " to " + i*i);
return i*i;
})
.limit(2)
.forEach(i -> System.out.println("---> " + i));
Prints:
Filtering 1: false
Filtering 2: true
Mapping 2 to 4
---> 4
Filtering 3: false
Filtering 4: true
Mapping 4 to 16
---> 16
Here, you can see elements are processed in batch of 2.
I have following doubts:
Why it did not processed only first two elements 1 and 2? That is, why the output is not just:
Filtering 1: false Filtering 2: true Mapping 2 to 4 ---> 4
Why it did not processed last four elements 5,6,7 and 8 and printed following?:
Filtering 5: false Filtering 6: true Mapping 6 to 36 ---> 36 Filtering 7: false Filtering 8: true Mapping 8 to 64 ---> 64