How to Filter Null Values from a Stream in Java

Published Mar 18, 2022  ∙  Updated May 2, 2022

Suppose we are streaming through a list of objects in Java.

List<String> lst = ...;

How can we filter for only non-null objects?

1. Using java.util.Objects

java.util.Objects has a method Objects::nonNull that will do just this.;

This is just a shorthand for the following: -> Objects.nonNull(obj));

2. Using a comparison operator

We can also simply check that an object does not equal null. -> obj != null);