Here I am going to show you how to filter null values from Java8 Stream.

Java 8 Stream Example:

Java8_FilterNullValues_Stream.java
package com.onlinetutorialspoint.java8;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Java8_FilterNullValues_Stream {
    public static void main(String[] args) {
        Stream<String> deptList = Stream.of(new String("IT"), new String("HR"),
                null, new String("Development"), null,
                new String("Recruitment"));
        showData(deptList);
    }

    public static void showData(Stream<String> deptList) {
        List<String> result = deptList.collect(Collectors.toList());
        result.forEach(System.out::println);
    }
}

Output:

Terminal
IT
HR
null
Development
null
Recruitment

On the above output, we can see that there are several null values. We can filter null values by the below solution.

Filter null values :

We can filter the null values by applying the condition in filter(x != null) method.

Java8_FilterNullValues_Stream.java
package com.onlinetutorialspoint.java8;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Java8_FilterNullValues_Stream {
    public static void main(String[] args) {
        Stream<String> deptList = Stream.of(new String("IT"), new String("HR"),
                null, new String("Development"), null,
                new String("Recruitment"));
        removeNullObjets(deptList);
    }

    public static void removeNullObjets(Stream<String> deptList) {
        List<String> result = deptList.filter(x -> x != null).collect(
                Collectors.toList());
        result.forEach(System.out::println);
    }

}

Output:

Terminal
IT
HR
Development
Recruitment

Happy Learning 🙂