How to Add Only Values that Exist from a List of Optionals in Java

Published Dec 23, 2021  ∙  Updated Jan 3, 2022

How can we easily filter a list of Optionals to only include those with values that are present?

Suppose we have an ArrayList lst as well as a list of Optional<String> called lstOfOptionals.

ArrayList<String> lst = new ArrayList<>();
ArrayList<Optional<String>> lstOfOptionals = getOptionalFromSomewhere();

We want to add only the Optional values that exist from lstOfOptionals into lst.

Add to list using a for loop

We could use isPresent() with an if block to add to the list.

for(Optional<String> opt : lstOfOptionals) {
  if (opt.isPresent()) {
    lst.add(opt.get());
  }
}

Or use ifPresent() to keep it slightly more concise.

for(Optional<String> opt : lstOfOptionals) {
  opt.ifPresent(lst::add)
}

Add to list using Stream API

We can also use the Stream API to achieve the same results.

lstOfOptionals
  .stream()
  .filter(Optional::isPresent)
  .map(Optional::get)
  .forEach(lst::add);