java – Finds the first element by predicate

No, the filter does not scan the entire stream. It is an intermediate operation that returns a slow flow (actually all the intermediate operations return a slow flow). To convince yourself, you can simply do the following test:

List<Integer> list = Arrays.asList(1, 10, 3, 7, 5);
int a = list.stream()
            .peek(num -> System.out.println("will filter " + num))
            .filter(x -> x > 5)
            .findFirst()
            .get();
System.out.println(a);

Which outputs:

will filter 1
will filter 10
10

It is seen that only the first two elements of the flow are actually processed.

So you can follow your own approach which is perfectly fine.

Leave a comment