DEV Community

Cover image for Filter Null Values from a List with Java8 Lambda
Gunnar Gissel
Gunnar Gissel

Posted on • Edited on • Originally published at gunnargissel.com

Filter Null Values from a List with Java8 Lambda

A common task with Java streams is to clean up the input data so later steps can work without thinking too hard. Likely the #1 most common cleanup step is to remove nulls from a Collection.

Streams make it easy:

myCollection.stream()
  .filter(Objects::nonNull)
  .do.what.you.need
Enter fullscreen mode Exit fullscreen mode

Compare with the classic approaches:

while(myCollection.remove(null));
// do what you need, but you better not need that original list, because it's gone...
myCollection.removeAll(Collections.singleton(null));
// do what you need, but you better not need that original list, because it's gone...
Enter fullscreen mode Exit fullscreen mode

Like the stream approach, these are short and sweet, but unlike the stream approach they modify the original list. The first example is also pretty slow.

I like the stream approach because I can chain additional tasks after the filter task, including map. sorted, reduce and more!. I find the traditional imperative iterative approach to be not only wordier, but conceptually harder to follow.

Top comments (4)

Collapse
 
pnaranja profile image
Paul

I use streams all the time to filter out results from my collections as well!

I know your title says "Java8", but note that Java 9 has Optional::stream

So now:
.map(this::lookupSettingByName)
.filter(Optional::isPresent)
.map(Optional::get)

Can be transformed to:
.map(this::lookupSettingByName)
.flatMap(Optional::stream)

Here's a reference link - iteratrlearning.com/java9/2016/09/...

Though I understand the filter -> map approach can be more readable

Collapse
 
monknomo profile image
Gunnar Gissel

That's a cool thing, for sure!

Collapse
 
roccoprobe profile image
rocco probe

Yup, .filter(Objects::nonNull) is definitely sweet, but one must ask... Why store nulls in a collection in the first place? :)

Collapse
 
monknomo profile image
Gunnar Gissel

You have to go to war with the collection you have; or at least, the collections you are given.

Besides, in some contexts, a null at some collection position has a meaning that it lacks in other contexts.

Let's see if I can come up with a concrete example...

In the context of a revolver, I can imagine a collection where nulls are important - you want to know chamber 5 is empty. But in the context of knowing something about the collection bullets in the revolver, we can ignore the nulls.

There are also Swing UI things - JList, JComboBox, etc. where nulls in collections are useful, but I expect the Swing developer is a marginal case these days.