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.
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.