Issue
I want to collect an Optional
into a List
, so that I end up with a list with a single element, if the optional is present or an empty list if not.
They only way I came up with (in Java 11) is going through a Stream:
var maybe = Optional.of("Maybe");
var list = maybe.stream().collect(Collectors.toList());
I know, this should be rather efficient anyway, but I was wondering, if there is an easier way to convert the Optional into a List without using an intermediate Stream?
Solution
I think that the most idiomatic way would be to use Optional.map
:
var maybe = Optional.of("Maybe");
var list = maybe.map(List::of).orElse(Collections.emptyList());
Or, if you don't want to create an empty list that might end up being not used at the end:
var list = maybe.map(List::of).orElseGet(Collections::emptyList);
Answered By - fps
Answer Checked By - Marilyn (JavaFixing Volunteer)