Java 8 Stream filter null values

In this source code example, we show how to filter Stream of null values in Java 8 with an example.

Java 8 Stream filter null values


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

public class JavaStreamFilterRemoveNulls {

    public static void main(String[] args) {

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

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

        System.out.println(result);
    }
}

Output:

[cup, forest, sky, book, theatre]

Comments