Java 8 - lazy pricing?

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?

+4
source share
1 answer

Here's the key: composition

arr.stream()
       .filter(Lazy::isGreater)
       .filter(Lazy::isEven)
       .map(Lazy::doubleIt)
       .findFirst();

This seems harmless, but now this value:

 arr.stream()
       .filter(Lazy::isGreater)

You can pass it to a method and build on it.

? , . .

, Stream . , , . JVM , -, , , , , .

+3

Source: https://habr.com/ru/post/1615959/


All Articles