Array Find Element (findFirst)Use filter and findFirst to find elements in an array. Find the first matching element with a predicate.
This page was last reviewed on May 18, 2023.
Array, find elements. 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.
Array data. 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
Example program. Here is an example program that uses Arrays.stream. The int array is passed to Arrays.stream and is transformed into an IntStream.
Next We call filter() with a predicate method to get elements with values equal to or exceeding 20.
Then We invoke FindFirst to get an OptionalInt—the first matching int. We call isPresent to see if a match was found.
Finally We use 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
Some notes. 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.
And If the program is using many streams, we can combine other filtering operations in the same statements. Code becomes clearer.
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 18, 2023 (edit).
© 2007-2024 Sam Allen.