Find first element by predicate
To find the first element in a list that matches a certain condition, you can use the stream()
method to create a stream from the list, and then use the filter()
method to specify the condition that the element should satisfy. Finally, you can use the findFirst()
method to get the first element in the stream that matches the condition, or findAny()
if you don't care which element you get.
Here's an example of how you could find the first element in a list of integers that is greater than 10:
List<Integer> list = Arrays.asList(1, 20, 3, 40, 5, 60);
Integer first = list.stream()
.filter(x -> x > 10)
.findFirst()
.orElse(null);
System.out.println(first); // 20
If the stream is empty or no elements match the condition, the findFirst()
method returns an empty Optional
. You can use the orElse()
method to specify a default value to be returned in this case.
You can also use the findAny()
method instead of findFirst()
if you don't care which element you get, as long as it matches the condition. This can be more efficient in some cases, because it can stop searching as soon as it finds any matching element, rather than searching for the first element.
Integer any = list.stream()
.filter(x -> x > 10)
.findAny()
.orElse(null);
System.out.println(any); // 20
Note that the findFirst()
and findAny()
methods both return an Optional
object, which is a container that may or may not contain a value. To get the value itself, you can use the get()
method or one of the other methods provided by Optional
, such as orElse()
, orElseGet()
, or orElseThrow()
.