Java Remove Null Values from List

Remove Null Values from List in Java

Learn how to remove null values from list in Java using core Java, libraries, and Java 8 approaches.

1. Introduction

Removing nulls from a list in Java is a common task when working with collections. Null values can cause unexpected behavior, especially when processing lists. This guide explains how to remove null values from a list in Java using core Java, Java 8 Streams, and third-party libraries.

2. Why Remove Null Values from a List?

  • Prevent Errors: Null values can cause NullPointerException, breaking your application logic.
  • Clean Data Processing: Removing null elements ensures your data is consistent and reliable.
  • Simplify Logic: A list without null values is easier to process and debug.


3. Approaches to Remove Null Values from List in Java

Let’s explore various methods to achieve this, from traditional techniques to modern solutions.

3.1. Using a for Loop

A simple for loop can be used to remove null values manually.

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

public class RemoveNulls {

    public static void main(String[] args) {
    
        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add(null);
        list.add("Spring");
        list.add(null);

        System.out.println("List containing null values: " + list);

        for (int i = 0; i < list.size(); i++) {
            if (list.get(i) == null) {
                list.remove(i);
                i--; // Adjust index after removal
            }
        }

        System.out.println("List after removing nulls: " + list);
    }
}
RemoveNulls.java

Explanation:

  • The for loop iterates through the list using an index i. When a null value is found (list.get(i) == null), it is removed using list.remove(i).
  • After a removal, the index is decremented (i--) to ensure the loop does not skip the next element, as the list shrinks after each removal.

    Output:

    List containing null values: [Java, null, Spring, null]
    List after removing nulls: [Java, Spring]
    
    CMD

    This logic ensures all null values are removed while correctly handling changes to the list size during iteration.



    3.2. Using an Iterator

    Iterate through the list with an Iterator, and use its remove() method when a null value is encountered. Using an Iterator is safer as it also prevents ConcurrentModificationException.

    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    
    public class RemoveNulls {
    
        public static void main(String[] args) {
    
            List<String> list = new ArrayList<>();
            list.add("Java");
            list.add(null);
            list.add("Spring");
            list.add(null);
    
            System.out.println("List containing null values: " + list);
    
            Iterator<String> iterator = list.iterator();
            while (iterator.hasNext()) {
                if (iterator.next() == null) {
                    iterator.remove();
                }
            }
    
            System.out.println("List after removing nulls: " + list);
        }
    }
    
    RemoveNulls.java

    Explanation:

    • An Iterator is used to traverse the list. The iterator.next() method retrieves each element, and the if condition checks if the element is null. If a null value is found, it is removed using the iterator.remove() method.

    Output:

    List containing null values: [Java, null, Spring, null]
    List after removing nulls: [Java, Spring]
    
    CMD

    This approach avoids issues with concurrent modification and ensures all null values are removed efficiently while iterating through the list.



    3.3. Using Java 8 Streams Filter Method

    Java 8 provides a simple way to remove null values from a list by using the filter method. This method goes through the list and excludes any null elements, creating a new list with only the non-null values. It’s a clean and efficient way to handle null values in a collection.

    import java.util.ArrayList;
    import java.util.List;
    import java.util.Objects;
    import java.util.stream.Collectors;
    
    public class RemoveNulls {
    
        public static void main(String[] args) {
    
            List<String> list = new ArrayList<>();
            list.add("Java");
            list.add(null);
            list.add("Spring");
            list.add(null);
    
            System.out.println("List containing null values: " + list);
    
            List<String> filteredList = list.stream()
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
    
            System.out.println("List after removing nulls: " + filteredList);
        }
    }
    RemoveNulls.java

    Explanation:

    • In this code, the stream() method is called on the list to create a stream of its elements. The filter(Objects::nonNull) operation is then applied to the stream, which filters out all null values and keeps only the non-null elements.
    • After filtering, the collect(Collectors.toList()) method collects the results into a new list, filteredList, containing only the non-null values.

    Output:

    List containing null values: [Java, null, Spring, null]
    List after removing nulls: [Java, Spring]
    
    CMD

    Note: The same approach can be used with parallel streams (parallelStream()) to process elements in parallel for better performance with large datasets. However, when using parallel streams, the order of the filtered elements may not be guaranteed.



    3.4. Using List removeIf Method

    The removeIf method is a convenient way to remove null values from a list in Java. It allows you to specify a condition (like null) and removes any elements that match the condition directly from the list, modifying the list in place without the need for additional intermediate collections.

    import java.util.ArrayList;
    import java.util.List;
    import java.util.Objects;
    
    public class RemoveNulls {
    
        public static void main(String[] args) {
    
            List<String> list = new ArrayList<>();
            list.add("Java");
            list.add(null);
            list.add("Spring");
            list.add(null);
    
            System.out.println("List containing null values: " + list);
    
            list.removeIf(Objects::isNull);
    
            System.out.println("List after removing nulls: " + list);
        }
    }
    RemoveNulls.java

    Explanation:

    • The removeIf(Objects::isNull) method removes all null values from a list by checking each element with the condition Objects::isNull. If an element is null, it is removed directly from the list, modifying the original list in place.

    Output:

    List containing null values: [Java, null, Spring, null]
    List after removing nulls: [Java, Spring]
    
    CMD

    This is a simple and efficient way to eliminate null values from a list without creating a new one.



    3.5. Using Google Guava

    Google Guava provides an elegant and functional approach to removing null values from a list. We can either modify the original list or create a new list without nulls using Guava’s Iterables.removeIf() and Iterables.filter() methods.

    Guava Dependency: To use Guava in your project, add the following dependency to your pom.xml:

    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>33.3.1-jre</version>
    </dependency>
    
    pom.xml


    You can find the latest version of Guava on Maven Central.

    Example 1: Modifying the Source List with Iterables.removeIf()

    import com.google.common.base.Predicates;
    import com.google.common.collect.Iterables;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class RemoveNulls {
    
        public static void main(String[] args) {
    
            List<String> list = new ArrayList<>();
            list.add("Java");
            list.add(null);
            list.add("Spring");
            list.add(null);
    
            System.out.println("List containing null values: " + list);
    
            Iterables.removeIf(list, Predicates.isNull());
    
            System.out.println("List after removing nulls: " + list);
        }
    }
    
    RemoveNulls.java

    Output:

    List containing null values: [Java, null, Spring, null]
    List after removing nulls: [Java, Spring]
    
    CMD

    As seen, Iterables.removeIf() directly modifies the original list, removing all null elements.

    Example 2: Creating a New List Without Nulls Using Iterables.filter()

    import com.google.common.base.Predicates;
    import com.google.common.collect.Iterables;
    import com.google.common.collect.Lists;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class RemoveNulls {
    
        public static void main(String[] args) {
    
            List<String> list = new ArrayList<>();
            list.add("Java");
            list.add(null);
            list.add("Spring");
            list.add(null);
    
            System.out.println("List containing null values: " + list);
    
            List<String> modifiedList = Lists.newArrayList(
                    Iterables.filter(list, Predicates.notNull()));
    
            System.out.println("List after removing nulls: " + modifiedList);
        }
    }
    RemoveNulls.java

    Output:

    List containing null values: [Java, null, Spring, null]
    List after removing nulls: [Java, Spring]
    
    CMD

    Here, Iterables.filter() creates a new list that contains only non-null elements, leaving the original list unchanged.



    3.6. Using Apache Commons Collections

    Apache Commons Collections provides a clean, functional way to filter out null values from a list using CollectionUtils.filter() combined with PredicateUtils.notNullPredicate().

    Apache Commons Collections Dependency: To use Apache Commons in your project, add the following dependency to your pom.xml:

    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-collections4</artifactId>
      <version>4.5.0-M2</version>
    </dependency>
    
    pom.xml


    You can find the latest version of Apache Commons Collections on Maven Central.

    Example: Modifying the Original List with CollectionUtils.filter()

    import org.apache.commons.collections4.CollectionUtils;
    import org.apache.commons.collections4.PredicateUtils;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class RemoveNulls {
    
        public static void main(String[] args) {
    
            List<String> list = new ArrayList<>();
            list.add("Java");
            list.add(null);
            list.add("Spring");
            list.add(null);
    
            System.out.println("List containing null values: " + list);
    
            CollectionUtils.filter(list, PredicateUtils.notNullPredicate());
    
            System.out.println("List after removing nulls: " + list);
        }
    }
    RemoveNulls.java

    Output:

    List containing null values: [Java, null, Spring, null]
    List after removing nulls: [Java, Spring]
    
    CMD


    As seen, CollectionUtils.filter() directly modifies the original list by removing all null values. This approach is simple and effective for filtering nulls from the list.



    4. Things to Consider

    Here are some important considerations to keep in mind while removing nulls:

    • List Mutability: Some methods modify the original list, while others create a new one. Choose based on your needs.
    • Thread Safety: Ensure thread safety when accessing or modifying the list from multiple threads.
    • Performance: For small lists, manual methods (like for loop or Iterator) work fine. For large lists, consider using Java Streams or libraries like Google Guava for efficiency.

    5. FAQs

    Can null values cause NullPointerException in Java?

    Is it better to use Streams or plain loops for null removal?



    6. Conclusion

    In conclusion, removing null values from a list in Java is an essential task for maintaining clean and reliable code. By leveraging simple techniques, such as using removeIf() or streams, you can ensure that your lists are free of nulls, avoiding potential errors or unwanted behavior in your applications. Whether you’re working with core Java or third-party libraries, these methods streamline the process and help you focus on writing more efficient and maintainable code.

    7. Learn More

    #

    Interested in learning more?

    How to Remove Duplicates from List in Java



    Add a Comment

    Your email address will not be published.