1.Using filter()
One option in Java 8 is to filter out the values with Optional::isPresent
and then perform mapping with the Optional::get
function to extract values:
ArrayList<Test> testlist = valueList.stream()
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
2.Using flatMap()
Another option is use flatMap with a lambda expression that converts an empty Optional to an empty Stream instance, and non-empty Optional to a Stream instance containing only one element:
ArrayList<Test> testlist = valueList.stream()
.flatMap(t -> t.isPresent() ? Stream.of(t.get()) : Stream.empty())
.collect(Collectors.toList());
You can apply the same approach using method reference to converting an Optional to Stream:
ArrayList<Test> testlist = valueList.stream()
.flatMap(t -> t.map(Stream::of).orElseGet(Stream::empty))
.collect(Collectors.toList());
3.Java 9's Optional::stream
In Java 9, the stream() method has been added to the Optional class to improve its functionality.This is similar to the one showed in section 2, but this time we are using a predefined method for converting Optional instance into a Stream instance, If the Optional contains a value, then return a Stream containing the value. Otherwise, it returns an empty stream.
ArrayList<Test> testlist = valueList.stream()
.flatMap(Optional::stream)
.collect(Collectors.toList());