There is no find()
method on arrays. But with a stream, we can use filter()
to search for a matching element based on a predicate function.
With findFirst
, we can get the first matching (filtered) item. This approach may have benefits in some cases over a for
-loop. But usually a for
-loop is better.
In our example, we have an array of 3 integers. And we want to find the first integer that is greater than or equal to 20.
Array: 10, 25, 35 First: 25
Here is an example program that uses Arrays.stream
. The int
array is passed to Arrays.stream
and is transformed into an IntStream
.
filter()
with a predicate method to get elements with values equal to or exceeding 20.FindFirst
to get an OptionalInt
—the first matching int
. We call isPresent
to see if a match was found.getAsInt()
to access the first matching element. In this array, we get the value 25 (as it is greater than or equal to 20).import java.util.Arrays; import java.util.OptionalInt; import java.util.stream.IntStream; public class Program { public static void main(String[] args) { int[] values = { 10, 25, 35 }; // Use filter to find all elements greater than 20. IntStream result = Arrays.stream(values).filter(element -> element >= 20); // Find first match. OptionalInt firstMatch = result.findFirst(); // Print first matching int. if (firstMatch.isPresent()) { System.out.println("First: " + firstMatch.getAsInt()); } } }First: 25
This is not a simple way of finding an array element. Usually, this approach will only be helpful if other parts of the program are also using Streams.
With findFirst()
we can find an element in an array. We first create a stream. We then add a filter()
which allows findFirst
to retrieve a matching element of the kind needed.