In this guide, you will learn about the Optional stream() method in Java programming and how to use it with an example.
1. Optional stream() Method Overview
Definition:
The stream() method of the Optional class in Java is used to transform the Optional instance into a Stream. If a value is present inside Optional, this method returns a sequential Stream containing only that value, otherwise, it returns an empty Stream.
Syntax:
public Stream<T> stream()
Parameters:
- The method does not take any parameters.
Key Points:
- It is a terminal operation, meaning it doesn’t return a new Optional, but a Stream.
- It is useful when working with a collection of Optional objects and you want to perform Stream operations on the values present inside them.
- This method is available from Java 9 onwards.
2. Optional stream() Method Example
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.List;
import java.util.Arrays;
public class OptionalStreamExample {
public static void main(String[] args) {
// Create a list of Optional objects
List<Optional<String>> listOfOptionals = Arrays.asList(
Optional.empty(),
Optional.of("Hello"),
Optional.of("World"),
Optional.empty()
);
// Transform the list of Optionals into a Stream and filter out the empty Optionals
List<String> filteredValues = listOfOptionals.stream()
.flatMap(Optional::stream)
.collect(Collectors.toList());
System.out.println(filteredValues);
}
}
Output:
[Hello, World]
Explanation:
In this example, we created a list containing several Optional objects, some of which are empty.
Using the stream() method along with flatMap(), we transformed each Optional in the list into a Stream, thus filtering out the empty Optional objects.
The result is a list containing the values present in the original Optional objects, demonstrating how Optional::stream() can be used to process values in a collection of Optional objects.
Comments
Post a Comment
Leave Comment