2

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)?

PurkkaKoodari
  • 6,703
  • 6
  • 37
  • 58

1 Answers1

7

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

Community
  • 1
  • 1
Avi
  • 21,182
  • 26
  • 82
  • 121
  • @Pietu1998 - I edited the question and it contains a link to an answer + question of mine that better explains this. – Avi Feb 20 '15 at 15:34