I went through Streams Video when I was embarrassed about how the Streams API gives a lazy imperative to loop.
Here's a typical loop code that checks the first number, which is more than three, and even then just prints it and returns.
List<Integer> arr = Arrays.asList(1, 2, 3, 5, 4, 6, 7, 8, 9);
for (int i : arr) {
System.out.println(" Checking if is Greater: " + i);
if (i > 3) {
System.out.println("checking if is Even " + i);
if (i % 2 == 0) {
System.out.println(i * 2);
break;
}
}
}
Here's the expected result:
Checking if is Greater: 1
Checking if is Greater: 2
Checking if is Greater: 3
Checking if is Greater: 5
Checking if is Even 5
Checking if is Greater: 4
Checking if is Even 4
8
Now here is the same code using the Streams API:
arr.stream()
.filter(Lazy::isGreater)
.filter(Lazy::isEven)
.map(Lazy::doubleIt)
.findFirst();
He also appreciates the same. So, how filter()does it provide something else that we cannot use with traditional loops?
source
share