1. Introduction

In Java, Lists can contain null elements. There might be scenarios where having nulls in the List is undesirable, and you might want to remove them. In this tutorial, we will demonstrate how to remove null elements from a List using Java.

2. Program Steps

1. Import the necessary classes.

2. Create a List containing some elements as null.

3. Use the removeIf() method from the List interface to remove null elements.

4. Print the original and the modified List.

3. Code Program

// Step 1: Importing necessary classes
import java.util.ArrayList;
import java.util.List;

public class RemoveNulls {

    public static void main(String[] args) {

        // Step 2: Creating a List containing some elements as null
        List<String> listWithNulls = new ArrayList<>();
        listWithNulls.add("Apple");
        listWithNulls.add(null);
        listWithNulls.add("Cherry");
        listWithNulls.add(null);
        listWithNulls.add("Banana");

        // Printing the original list
        System.out.println("Original List: " + listWithNulls);

        // Step 3: Using the removeIf() method to remove null elements
        listWithNulls.removeIf(element -> element == null);

        // Printing the modified list
        System.out.println("List Without Nulls: " + listWithNulls);
    }
}

Output:

Original List: [Apple, null, Cherry, null, Banana]
List Without Nulls: [Apple, Cherry, Banana]

4. Step By Step Explanation

Step 1: Import the necessary class, ArrayList, and interface, List.

Step 2: Create a List named listWithNulls and add some elements to it, including null elements.

Step 3: Use the removeIf() method with a lambda expression element -> element == null to remove all the null elements from the listWithNulls.

Finally, print the original listWithNulls and the modified listWithNulls to observe the removal of null elements.