EN
Java 8 - find first element in Stream
0 points
In this article, we would like to show you how to find the first element in Stream in Java.
Stream findFirst()
returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty. If the stream has no encounter order, then any element may be returned.
xxxxxxxxxx
1
Optional<T> findFirst()
Where:
Optional
- container object which may or may not contain a non-null value.- If a value is present,
isPresent()
will returntrue
andget()
will return the value.
- If a value is present,
T
- the type of objects.
In this example, we use the findFirst()
function on Stream of Strings.
xxxxxxxxxx
1
import java.util.Arrays;
2
import java.util.List;
3
import java.util.Optional;
4
5
public class Example {
6
7
public static void main(String[] args) {
8
// Create List of Strings
9
List<String> numbers = Arrays.asList("A", "B", "C", "D");
10
11
// Use Stream findFirst()
12
Optional<String> result = numbers.stream().findFirst();
13
14
// If the stream is empty returns empty Optional
15
if (result.isPresent()) {
16
System.out.println(result.get());
17
} else {
18
System.out.println("empty");
19
}
20
}
21
}
Output:
xxxxxxxxxx
1
A