In this tutorial, we will see “How to filter null values from ArrayList in Java 8?”. In order to remove null from the list, we are going to use Stream API introduced in Java 8.

In the below specified example, I’ve explained 2 different code approaches to achieve the same output:

  1. Anonymous Implementation
  2. Lambda Implementation

Filter/Remove null values from a List using Stream in Java 8...!!! Share on X

Example

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;

public class Filter_Null_List_Java8_Stream_Example {

    public static void main(String[] args) {

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

        users.add("noni");
        users.add("yogi");
        users.add("null");
        users.add("null");
        users.add("isha");
        users.add("yashi");
        users.add("yashu");
        users.add("null");


        //Original List
        System.out.println("Original List:\n");
        users.stream().forEach(System.out::println);


        //List after removing 'Null' values
        // 1. Anonymous Implementation
        System.out.println("\nNew List after removing 'null' (Anonymous Impl):\n");
        users.stream().filter(new Predicate <String> () {
            @Override
            public boolean test(String t) {
                return !t.contains("null");
            }
        }).forEach(new Consumer <String> () {
            @Override
            public void accept(String t) {
                System.out.println(t);
            }
        });
        System.out.println("\n");


        //List after removing 'Null' values
        // 2. Lambda Implementation
        System.out.println("New List after removing 'null' (Lambda Impl):\n");
        users.stream().filter(t - > !t.contains("null")).forEach(System.out::println);

    }

}

 

Output:

Original List:

noni
yogi
null
null
isha
yashi
yashu
null

New List after removing 'null' (Anonymous Impl):

noni
yogi
isha
yashi
yashu


New List after removing 'null' (Lambda Impl):

noni
yogi
isha
yashi
yashu

Filter/Remove null values from a List using Stream in Java 8...!!! Share on X

Do you like this Post? – then check my other helpful posts:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts