This example shows how Java 8 streams are lazy.
package com.logicbig.example;
import java.util.stream.IntStream;
import static com.logicbig.example.LogUtil.log;
public class LazyExample {
public static void main (String[] args) {
IntStream stream = IntStream.range(1, 5);
stream = stream.peek(i -> log("starting", i))
.filter(i -> {
log("filtering", i);
return i % 2 == 0;
})
.peek(i -> log("post filtering", i));
log("Invoking terminal method count.");
log("The count is", stream.count());
}
}
Output
15:40:47.815 - Invoking terminal method count.
15:40:47.825 - starting - 1
15:40:47.827 - filtering - 1
15:40:47.828 - starting - 2
15:40:47.830 - filtering - 2
15:40:47.831 - post filtering - 2
15:40:47.833 - starting - 3
15:40:47.834 - filtering - 3
15:40:47.836 - starting - 4
15:40:47.837 - filtering - 4
15:40:47.839 - post filtering - 4
15:40:47.840 - The count is - 2
Original Post