EN
Java 8 - find first element in Stream that matches criteria
0 points
In this article, we would like to show you how to find the first element in Stream that matches the criteria in Java 8.
In the example below, we use:
stream()
- to create a stream from the List,filter()
- to specify the criteria (in our case if the element starts with "B
"),findFirst()
- to return the first value that matches the criteria,orElse()
- to return null if none of the elements matches.
Practical example:
xxxxxxxxxx
1
import java.util.*;
2
3
public class Example {
4
5
public static void main(String[] args) {
6
// create list of strings
7
List<String> letters = Arrays.asList("A1", "B1", "A2", "B2");
8
9
// find first element that matches the criteria
10
String result = letters.stream()
11
.filter(x -> x.startsWith("B")) // <----- example criteria
12
.findFirst()
13
.orElse(null);
14
15
System.out.println(result); // B1
16
}
17
}
Output:
xxxxxxxxxx
1
B1