Skip to content

Java Stream filter null values example

Ramesh Fadatare edited this page Jul 11, 2019 · 1 revision

The Java example filters out null values.

Java Stream filter null values example

We have a list of words. With the Stream filtering operation, we create a new list with null values removed.

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

public class JavaStreamFilterRemoveNulls {

    public static void main(String[] args) {

        List<String> words = Arrays.asList("cup", null, "forest",
                "sky", "book", null, "theatre");

        List<String> result = words.stream().filter(w -> w != null)
                .collect(Collectors.toList());

        System.out.println(result);
    }
}

Output:

[cup, forest, sky, book, theatre]

There are no null values in the final output.

In the body of the lambda expression, we check that the value is not null. The collect() method is a terminal operation that creates a list from the filtered stream:

List<String> result = words.stream().filter(w -> w != null)
        .collect(Collectors.toList());
Clone this wiki locally