This method is supported since Java 9.
This method is used to create a new Stream object from an Optional object in Java.
If the Optional object contains a value, this method will return the Stream object containing that value, otherwise, it returns an empty Stream object.
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.huongdanjava.javaexample; import java.io.IOException; import java.util.Optional; import java.util.stream.Stream; public class Example { public static void main(String[] args) throws IOException { String s = "Khanh"; Optional<String> opt = Optional.ofNullable(s); Stream<String> stream = opt.stream(); stream.forEach(System.out::println); } } |
Result:
In the case where we have a List of Optional objects, one of them is empty, the stream() method of the Optional object can help us remove these Optional empty objects.
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.huongdanjava.javaexample; import java.io.IOException; import java.util.List; import java.util.Optional; import java.util.stream.Stream; public class Example { public static void main(String[] args) throws IOException { List<Optional<String>> names = List.of( Optional.of("Khanh"), Optional.empty(), Optional.of("Quan")); Stream<String> stream = names.stream().flatMap(Optional::stream); stream.forEach(System.out::println); } } |
You can refer to the flatMap() method of the Stream object here.
Result: