How to Filter a List of Optionals in Java


How can we filter a List or Stream of Optionals in Java?

Suppose we have a list of optionals opts.

List<Optional<String>> opts;

1. Using filter()

We can filter the stream using Optional::isPresent and Optional::get to extract the value from the Optional.

List<String> list = opts
  .stream()
  .filter(Optional::isPresent)
  .map(Optional::get)
  .collect(Collectors.toList());

2. Using flatMap()

We can also use flatMap() to return a stream of values. The stream will contain the single Optional value if it exists, otherwise, it will be empty.

List<String> list = opts
  .stream()
  .flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty))
  .collect(Collectors.toList());

3. Using flatMap(Optional::stream)

If we’re using Java 9+, we can use flatMap(Optional::stream), which runs the same logic as the previous approach.

List<String> list = opts
  .stream()
  .flatMap(Optional::stream)
  .collect(Collectors.toList());