How to Filter Null Values from a Stream in Java
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.
lst.stream().filter(Objects::nonNull);
This is just a shorthand for the following:
lst.stream().filter(obj -> Objects.nonNull(obj));
2. Using a comparison operator
We can also simply check that an object does not equal null
.
lst.stream().filter(obj -> obj != null);