Java Stream filter null values example

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]


Java ArrayList Source Code Examples


Comments