The stream() method of the java.util.Optional class returns a sequential Stream containing the value present in the Optional. When the Optional is empty, it returns an empty Stream.
- stream() was introduced in Java 9 and is useful when working with the Stream API.
- For a present Optional, the resulting stream contains exactly one element; for an empty Optional, the stream contains no elements.
Syntax
public Stream<T> stream()
Return Value: The stream() method returns a sequential Stream containing the value present in the Optional. If the Optional is empty, it returns an empty Stream.
Note: The programs below require JDK 9 or later.
Ways to Use stream() in Optional
The following examples demonstrate how stream() behaves with a present Optional and an empty Optional.
1. Using stream() with a Present Optional
The following program creates an Optional containing an integer value and converts it into a stream using stream().
Approach:
- Create an Optional containing the value 9455.
- Display the Optional.
- Call the stream() method to obtain a sequential stream.
- Use forEach() to display the stream element.
import java.util.Optional;
public class OptionalStreamDemo {
public static void main(String[] args) {
Optional<Integer> op = Optional.of(9455);
System.out.println("Optional: " + op);
System.out.println("Elements in Stream:");
op.stream().forEach(System.out::println);
}
}
Output
Optional: Optional[9455] Elements in Stream: 9455
Explanation: The Optional contains the value 9455, so stream() returns a sequential stream containing one element. The forEach() method prints that element.
2. Using stream() with an Empty Optional
The following program creates an empty Optional and calls the stream() method on it.
Approach:
- Create an empty Optional.
- Display the Optional.
- Call the stream() method.
- Use forEach() to process the stream elements.
import java.util.Optional;
public class OptionalStreamDemo {
public static void main(String[] args) {
Optional<Integer> op = Optional.empty();
System.out.println("Optional: " + op);
System.out.println("Elements in Stream:");
op.stream().forEach(System.out::println);
}
}
Output
Optional: Optional.empty Elements in Stream:
Explanation:Ā TheĀ OptionalĀ is empty, soĀ stream()Ā returns an empty stream. Therefore,Ā forEach()Ā has no element to process and nothing is printed after the heading.