Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all Optional empty/null values from arraylist in java

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?

like image 262
Niraj Sonawane Avatar asked Dec 29 '17 09:12

Niraj Sonawane


People also ask

Is optional empty null Java?

An Optional object in Java is a container object that can hold both empty and a non-null values. If an Optional object does contain a value, we say that it is present; if it does not contain a value, we say that it is empty.

Does optional empty return null?

An Optional always contains a non-null value or is empty, yes, but you don't have an Optional, you have a reference of type Optional pointing to null.

How do you remove null values from a set?

A HashSet , being a set, only contains one "copy" of any object, which also means that it can only contain one instance of null . Thus, you can just use HashSet. remove(null) .


1 Answers

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 a Stream 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());
like image 143
Naman Avatar answered Sep 17 '22 22:09

Naman