patternjavaMajor
Filtering out empty Optionals
Viewed 0 times
emptyoptionalsoutfiltering
Problem
I want to convert my list of optional strings to a list of strings by getting rid of the empty
Is there a shorter version for achieving this than the following code (except statically importing the methods of
Optionals.Is there a shorter version for achieving this than the following code (except statically importing the methods of
Collectors)?List> stringsMaybe = Arrays.asList(Optional.of("Hi"),
Optional.empty(), Optional.of(" there!"));
List strings = stringsMaybe
.stream()
.filter(Optional::isPresent)
.collect(Collectors.mapping(Optional::get, Collectors.toList()));Solution
It's more idiomatic to use
Without introducing a helper method or a custom collector, that's the shortest and clearest way to do this.
Since Java 9,
.map on the stream instead of Collectors.mapping:stringsMaybe.stream()
.filter(Optional::isPresent)
.map(Optional::get)
.collect(toList());Without introducing a helper method or a custom collector, that's the shortest and clearest way to do this.
Since Java 9,
Optional offers a stream method, enabling you to do .flatMap(Optional::stream) instead of .filter(...).map(...).Code Snippets
stringsMaybe.stream()
.filter(Optional::isPresent)
.map(Optional::get)
.collect(toList());Context
StackExchange Code Review Q#109294, answer score: 37
Revisions (0)
No revisions yet.