Reputation: 10539
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?
Upvotes: 5
Views: 5473
Reputation: 34460
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);
Upvotes: 7
Reputation: 22977
Okay, I'll just post it as an answer.
List.of(maybe.get())
. Of course this assumes that there actually is a value present within the optional. Otherwise: var list = maybe.isPresent() ? List.of(maybe.get()) : List.of()
.
Is it easier? Perhaps not. Is it without an intermediate stream? Yes.
Upvotes: 4