Middle
What is findFirst() and a terminal operation in the Stream API?
sobes.tech AI
Answer from AI
The findFirst() method in the Stream API is used to obtain the first element from a stream that matches the given conditions. It is a terminal operation, meaning it initiates stream processing and returns a result.
Terminal operations are those that conclude stream processing and return a specific result (such as an element, collection, or number) or a side effect. After a terminal operation, the stream is considered "consumed" and cannot be used further.
Example of using findFirst():
List<String> list = Arrays.asList("apple", "banana", "cherry");
Optional<String> first = list.stream()
.filter(s -> s.startsWith("b"))
.findFirst();
first.ifPresent(System.out::println); // Will print "banana"
Here, findFirst() returns the first element starting with the letter "b". If no such element exists, an empty Optional is returned.