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

Published Dec 23, 2021  ∙  Updated May 2, 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()) {

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

for(Optional<String> opt : lstOfOptionals) {

Add to list using Stream API

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