Java 8 Stream - Why is the filter method not executing?

I am studying filtering using java thread. But the stream after filtering does not print anything. I think the filter method is not executing. My filtering code is as follows:

Stream.of("d2", "a2", "b1", "b3", "c") .filter(s -> { s.startsWith("b"); System.out.println("filter: " + s); return true; }); 

Compilation error and exception does not exist. Any suggestion?

+5
source share
1 answer

filter is an intermediate operation that will be performed only if the Stream pipeline ends in a terminal operation.

For instance:

 Stream.of("d2", "a2", "b1", "b3", "c") .filter(s -> { s.startsWith("b"); System.out.println("filter: " + s); return true; }) .forEach (System.out::println); 

Be that as it may, your filter method is useless, as it always returns true and therefore does not perform filtering.

+12
source

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


All Articles