How to filter null values using Java 8 Stream API

We can make use of the intermediate filter() operation on a stream to filter out the null values as follows.

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class Main {

    public static void main(String[] args) {

        List<String> namesList = new ArrayList<>();

        List<String> namesWithoutNulls =

        System.out.println("Name list with nulls: " + namesList);
        System.out.println("Name list without nulls: " + namesWithoutNulls);


Name list with nulls: [Mike, Sam, null, Alex, null]
Name list without nulls: [Mike, Sam, Alex]

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail:

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap