Reputation: 11055
I need to remove all empty/null values from List<Optional<String>>
.
Example:
List<Optional<String>> list = new ArrayList<>();
list.add(Optional.empty());
list.add(Optional.of("Str1"));
list.add(Optional.of("Str2"));
list.add(Optional.of("Str3"));
list.add(Optional.of("Str4"));
list.add(Optional.of("Str5"));
list.add(Optional.empty());
list.add(Optional.ofNullable(null));
Currently, I'm using one of the below approaches:
Way 1:
List<String> collect = list.stream()
.filter(Optional::isPresent)
.map(obj ->obj.get())
.collect(Collectors.toList());
Way 2:
List<Optional<String>> emptlist = new ArrayList<>();
emptlist.add(Optional.empty());
list.removeAll(emptlist);
Is there any other better way?
Upvotes: 20
Views: 9513
Reputation: 101
For anyone who wants to have a little fun or understand working of Optionals and Streams better (Java 8):
List<String> collect=list.stream().
map(z->z.map(Stream::of)).
flatMap(ox->ox.orElseGet(Stream::empty)).
collect(Collectors.toList());
Upvotes: 1
Reputation: 31878
With Java9, you can do this using the newly added Optional::stream
API :
List<String> collect = list.stream()
.flatMap(Optional::stream)
.collect(Collectors.toList());
This method can be used to transform a
Stream
of optional elements to aStream
of present value elements.
Sticking with Java8, the Way1 in the question is good enough IMHO -
List<String> collect = list.stream()
.filter(Optional::isPresent)
.map(Optional::get) // just a small update of using reference
.collect(Collectors.toList());
Upvotes: 26
Reputation: 5369
removeIf
is the shortest way to do that :
list.removeIf(x -> !x.isPresent());
Upvotes: 8