Removing all Nulls from a List in Java

1. Remove Nulls From a List Using Plain Java

The Java Collections Framework offers a simple solution for removing all null elements in the List – a basic while loop:

@Test
public void givenListContainsNulls_whenRemovingNullsWithPlainJava_thenCorrect() {
    List<Integer> list = Lists.newArrayList(null, 1, null);
    while (list.remove(null));

    assertThat(list, hasSize(1));
}

Alternatively, we can also use the following simple approach:

@Test
public void givenListContainsNulls_whenRemovingNullsWithPlainJavaAlternative_thenCorrect() {
    List<Integer> list = Lists.newArrayList(null, 1, null);
    list.removeAll(Collections.singleton(null));

    assertThat(list, hasSize(1));
}

Note that both these solutions will modify the source list.

2. Remove Nulls From a List Using Google Guava

We can also remove nulls using Guava and a more functional approach, via predicates:

@Test
public void givenListContainsNulls_whenRemovingNullsWithGuavaV1_thenCorrect() {
    List<Integer> list = Lists.newArrayList(null, 1, null);
    Iterables.removeIf(list, Predicates.isNull());

    assertThat(list, hasSize(1));
}

Alternatively, if we don’t want to modify the source list, Guava will allow us to create a new, filter list:

@Test
public void givenListContainsNulls_whenRemovingNullsWithGuavaV2_thenCorrect() {
    List<Integer> list = Lists.newArrayList(null, 1, null, 2, 3);
    List<Integer> listWithoutNulls = Lists.newArrayList(
      Iterables.filter(list, Predicates.notNull()));

    assertThat(listWithoutNulls, hasSize(3));
}

3. Remove Nulls From a List Using Apache Commons Collections

Let’s now look at a simple solution using the Apache Commons Collections library using a similar functional style:

@Test
public void givenListContainsNulls_whenRemovingNullsWithCommonsCollections_thenCorrect() {
    List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
    CollectionUtils.filter(list, PredicateUtils.notNullPredicate());

    assertThat(list, hasSize(3));
}

Note that this solution will also modify the original list.

4. Remove Nulls From a List Using Lambdas (Java 8)

Finally – let’s look at a Java 8 solution using Lambdas to filter the List; the filtering process can be done in parallel or serial:

@Test
public void givenListContainsNulls_whenFilteringParallel_thenCorrect() {
    List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
    List<Integer> listWithoutNulls = list.parallelStream()
      .filter(Objects::nonNull)
      .collect(Collectors.toList());
}

@Test
public void givenListContainsNulls_whenFilteringSerial_thenCorrect() {
    List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
    List<Integer> listWithoutNulls = list.stream()
      .filter(Objects::nonNull)
      .collect(Collectors.toList());
}

public void givenListContainsNulls_whenRemovingNullsWithRemoveIf_thenCorrect() {
    List<Integer> listWithoutNulls = Lists.newArrayList(null, 1, 2, null, 3, null);
    listWithoutNulls.removeIf(Objects::isNull);

    assertThat(listWithoutNulls, hasSize(3));
}

And that’s it – some quick and very useful solutions for getting rid of all null elements from a List.

5. Conclusion

In this article, we were able to explore the different approaches we can have to remove nulls from a List using Java, Guava or Lambdas.

The implementation of all of these examples and snippets can be found in the GitHub project. This is a Maven-based project so it should be easy to import and run.

Related posts:

Java Program to Generate All Possible Subsets with Exactly k Elements in Each Subset
What is a POJO Class?
Giới thiệu SOAP UI và thực hiện test Web Service
Request Method Not Supported (405) in Spring
Guide To CompletableFuture
Java Program to Check if it is a Sparse Matrix
Java Program to Generate Random Numbers Using Middle Square Method
Java Program to Find Location of a Point Placed in Three Dimensions Using K-D Trees
Xây dựng ứng dụng Client-Server với Socket trong Java
Send email with SMTPS (eg. Google GMail)
Java Program to Use Dynamic Programming to Solve Approximate String Matching
Registration with Spring Security – Password Encoding
Java Program to Test Using DFS Whether a Directed Graph is Weakly Connected or Not
Java Program to Perform Polygon Containment Test
Giới thiệu java.io.tmpdir
Java Program to Implement LinkedHashSet API
Cơ chế Upcasting và Downcasting trong java
Java Program to Implement Horner Algorithm
Inheritance and Composition (Is-a vs Has-a relationship) in Java
Java Program to Optimize Wire Length in Electrical Circuit
Creating a Generic Array in Java
Hướng dẫn sử dụng Printing Service trong Java
A Guide to the Java ExecutorService
Function trong Java 8
Java Program to Implement Bellman-Ford Algorithm
Lập trình mạng với java
A Guide to ConcurrentMap
Java Program to find the maximum subarray sum using Binary Search approach
Java Program to Find Transpose of a Graph Matrix
Returning Custom Status Codes from Spring Controllers
Quick Guide to java.lang.System
Reading an HTTP Response Body as a String in Java