Remove Optional Empty/Null values from list

In this Article , we’ll Discuss, How we can Convert Stream of Optional elements to a Stream of present value elements.

Java 8 has added Optional type to avoid null pointer exception.

lets say we have List<Optional<String>> and for further processing we want List<Strings>.
In This case we need to remove the null and empty elements from stream and convert it into a Stream of present value elements.

Convert Stream of Optional elements to a Stream of present value elements
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//Input List 
List<Optional<String>> list = new ArrayList<>();
list.add(Optional.empty());
list.add(Optional.of("Str1"));
list.add(Optional.of("Str2"));
list.add(Optional.empty());
list.add(Optional.ofNullable(null));
//Using Filter
List<String> listWithoutNull = list.stream()
.filter(Optional::isPresent)
.map(obj ->obj.get())
.collect(Collectors.toList());

//Using removeIf (if that list supports removal )
list.removeIf(iteam->!iteam.isPresent());



Java 9

In java 9 We can easily convert Stream of optionals to a stream of present values.
Using newly addded Optional::stream API

java 9
1
2
3
List<String> listWithoutNull = list.stream()
.flatMap(Optional::stream)
.collect(Collectors.toList());
Share Comments