Finding the First Element that Matches a Predicate

suggest change

It is possible to find the first element of a Stream that matches a condition.

For this example, we will find the first Integer whose square is over 50000.

IntStream.iterate(1, i -> i + 1) // Generate an infinite stream 1,2,3,4...
    .filter(i -> (i*i) > 50000) // Filter to find elements where the square is >50000
    .findFirst(); // Find the first filtered element

This expression will return an OptionalInt with the result.

Note that with an infinite Stream, Java will keep checking each element until it finds a result. With a finite Stream, if Java runs out of elements but still can’t find a result, it returns an empty OptionalInt.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Streams:
* Finding the First Element that Matches a Predicate

Table Of Contents
2 Streams
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap