Emil Kantis Emil Kantis - 3 months ago 7
Java Question

Merging List<T> and List<Optional<T>>

Given:

List<Integer> integers = new ArrayList<>(Arrays.asList(
10, 12
));

List<Optional<Integer>> optionalIntegers = Arrays.asList(
Optional.of(5),
Optional.empty(),
Optional.of(3),
Optional.of(2),
Optional.empty()
);

List<Integer> unwrappedOptionals = optionalIntegers.stream()
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());

integers.addAll(unwrappedOptionals);


Is there some better way of unwrapping
Optional
s, or other way of merging them both into a
List<Integer>
? It feels extremely wasteful to collect them into a new
List
before doing
addAll()
.

Answer

You could use the other form of ifPresent

ifPresent(Consumer<T>) void

With a simple forEach one could write:

optionalIntegers.stream().forEach(optional -> optional.ifPresent(integers::add));