Is there a way to find the first element to match a Predicate?
filtering, java, java-stream, performance, predicate
Solution
It does exactly what you want. It doesn't run over all the elements. The `filter` method creates a stream and on top of it `findFirst` creates another stream.
So when you try to get the element of the stream that was created after `findFirst()` you'll get only the first one that matches the predicate.
Best way to check that is to add a print line or something like that inside the predicate.
Create a stream of integers for example from 0 to 10 and create a predicate that prints the number and then checks if it's divided by 3. You'll get this printed out: 0, 1, 2, 3 and that's it.
I wrote a question + answer in the past to explain in more details how it works: Understanding java 8 stream's filter method
Problem
With Java 8+, you can easily find all elements of a collection that match a `Predicate`. ``` someCollection.stream().filter(somePredicate) ``` You could then find the first element: ``` someCollection.stream().filter(somePredicate).findFirst() ``` The problem with this, though, is that it runs the `Predicate` against all the elements. Is there a clean way to only run the `Predicate` against elements until the first match is found, and then return it, like `anyMatch` does (but returns a `boolean` telling if one was found)?