Overview

Java List and Map may contain null values (elements). And sometimes we need to filter those null elements to avoid NullPointerException before going to process it using stream API. We can do it by filtering null elements from stream using Stream.filter(). Let’s go throw the examples of Java stream filter null values from the steam of List, Map values and Set of Map.Entry

Example 1: Filter null values from List

In this example, going to filter all null elements from a stream of List using Objects class static nonNull method introduces in Java 8.

Objects.nonNull() method returns true if the provided reference is non-null otherwise returns false, and based on that Stream.filter() method will decide whether an element should filter or continue.

Alternate solution is pass predicate function or lambda expression which return boolean value whether current element is null or not like: filter(element -> element != null)

package com.javadeveloperzone;

import java.util.*;

public class FilterNullElement {

    public static void main(String[] args) {

        String[] strArray = new String[] {"ONE", null, "THREE", null, "FIVE"};  //Two elements second and fourth are null
        List<String> elements = new ArrayList<>(Arrays.asList(strArray));

        System.out.println("# Before Filter");
        elements.forEach(System.out::println);

        System.out.println("# After Filter");
        elements.stream()
                .filter(Objects::nonNull)       // It will filter null elements
                //another way is filter(element -> element != null)
                .forEach(System.out::println);
    }
}

Output

# Before Filter
ONE
null
THREE
null
FIVE

# After Filter
ONE
THREE
FIVE      // Here both null elements are filtered

Example 2: Filter null values from Map values

In this example, going to filter all null value elements from the stream of Map values using Objects class static nonNull method.

package com.javadeveloperzone;

import java.util.*;

public class FilterNullElement {

    public static void main(String[] args) {

        Map<Integer, String> elementMap = new HashMap<>();
        elementMap.put(1, "ONE");
        elementMap.put(2, null);
        elementMap.put(3, "THREE");
        elementMap.put(4, null);
        elementMap.put(5, "FIVE");

        System.out.println("# Before Filter null values");
        elementMap.values()
                 .forEach(System.out::println);

        System.out.println("# After Filter null values");
        elementMap.values()
                .stream()
                .filter(Objects::nonNull)
                .forEach(System.out::println);
    }
}

Output

# Before Filter null values
ONE
null
THREE
null
FIVE

# After Filter null values
ONE
THREE
FIVE       // Here both null values (Key: 2 and 4) are filtered

 

Example 3: Filter null values from Set of Map.Entry

In the following example, passed a lambda expression as an argument of filter function (which returns the boolean value true if both key and value of current map entry are not null else return false) to filter elements which contain either key or value as null.

package com.javadeveloperzone;

import java.util.*;

public class FilterNullElement {

    public static void main(String[] args) {

        Map<Integer, String> elementMap = new HashMap<>();
        elementMap.put(1, "ONE");
        elementMap.put(2, null);
        elementMap.put(null, "THREE");
        elementMap.put(4, null);
        elementMap.put(5, "FIVE");

        System.out.println("# Before Filter null keys and values");
        elementMap.entrySet()
                  .forEach(entry -> {
                      System.out.println(entry.getKey() + " => " + entry.getValue());
                  });

        System.out.println("# After Filter null keys and values");
        elementMap.entrySet()
                .stream()
                .filter(entry -> entry.getKey() != null && entry.getValue() != null)   //Filtered elements from map which has either Key or Value null
                .forEach(entry -> {
                    System.out.println(entry.getKey() + " => " + entry.getValue());
                });
    }
}

Output

# Before Filter null keys and values
1 => ONE
2 => null
null => THREE
4 => null
5 => FIVE

# After Filter null keys and values
1 => ONE
5 => FIVE     

//Here, entry of value "THREE" is filtered due to its Key is null and entry of key "2" and "4" are filtered because of its value is null

Conclusion

Java stream filter null values article shows you how to filter null elements from the stream of List, Map values, and Map entry set.

The same way we can filter null elements (values) from other Collection implementations using Stream.filter() method and pass the predicate function or lambda expression to filter null elements as per your requirements (for primitive-wrapper or custom java type).

References

Was this post helpful?
Let us know, if you liked the post. Only in this way, we can improve us.
Yes
No

Leave a Reply

Your email address will not be published. Required fields are marked *