Core Java

Java – Remove all nulls from a List

Introduction:

In this article, we’ll learn how to remove nulls from a Java List using plain-old Java, Java 8 lambda expression, and some third-party libraries.

So, let’s get started!

Removing nulls from a List In Java:

Let’s explore different ways in which we can remove nulls from a Java List:

1. Java 7 or lower versions:

When working with Java 7 or lower versions, we can use the below construct to remove all nulls from a List:

Java

@Test
public removeAllNullsFromListWithJava7OrLower() {
 
    List<String> list =
      new ArrayList<>(Arrays.asList("A", null, "B", null));
 
    list.removeAll(Collections.singleton(null));
 
    assertThat(list, hasSize(2));
}

Note that we have created a mutable list here. Attempting to remove nulls from an immutable list will throw java.lang.UnsupportedOperationException.

2. Java 8 or higher versions:

The approach for removing nulls from a Java List for Java 8 or higher versions is pretty intuitive and elegant:

@Test
public removeAllNullsFromListWithJava8() {
 
    List<String> list =
      new ArrayList<>(Arrays.asList("A", null, "B", null));
 
    list.removeIf(Objects::isNull);
 
    assertThat(list, hasSize(2));
}

We can simply use the removeIf() construct to remove all null values.

If we don’t want to alter the existing list and rather return a new list with all non-null values, we can have:

Java

@Test
public removeAllNullsFromListWithJava8() {
 
    List<String> list =
      new ArrayList<>(Arrays.asList("A", null, "B", null));
 
    List<String> newList = list.stream().filter(Objects::nonNull)
      .collect(Collectors.toList());
 
    assertThat(list, hasSize(4));
    assertThat(newList, hasSize(2));
}

We can learn more about Java 8 Stream Collectors here.

3. Apache Commons:

Apache Commons CollectionUtils class provides a filter(Iterable, Predicate) method that can also solve our purpose. The passed-in predicate is applied to all the elements in the list:

Java

@Test
public removeAllNullsFromListWithApacheCommons() {
 
    List<String> list =
      new ArrayList<>(Arrays.asList("A", null, "B", null));
 
    CollectionUtils.filter(list, PredicateUtils.notNullPredicate());
 
    assertThat(list, hasSize(2));
}

Thereby, filtering out all nulls from the existing list.

4. Google Guava:

The Iterables class in Guava provides removeIf(Iterable, Predicate) method to help us filter our values based on the given predicate. Let’s see how can we use it to our advantage:

Java

@Test
public removeAllNullsFromListUsingGuava() {
 
    List<String> list =
      new ArrayList<>(Arrays.asList("A", null, "B", null));
 
    Iterables.removeIf(list, Predicates.isNull());
 
    assertThat(list, hasSize(2));
}

Alternatively, if we don’t want to modify the existing list, Guava allows us to create a new filtered list:

Java

@Test
public removeAllNullsFromListUsingGuava() {
 
    List<String> list =
      new ArrayList<>(Arrays.asList("A", null, "B", null));
 
    List<String> newList = new ArrayList<>(
      Iterables.filter(list, Predicates.notNull()));
 
    assertThat(list, hasSize(4));
    assertThat(newList, hasSize(2));
}

Java

@Test
public removeAllNullsFromList() {
 
    List<String> list =
      new ArrayList<>(Arrays.asList("A", null, "B", null));
 
    List<String> newList = new ArrayList<>(
      Iterables.filter(list, Predicates.notNull()));
 
    assertThat(list, hasSize(4));
    assertThat(newList, hasSize(2));
}

Conclusion:

In this quick tutorial, we explored multiple ways in which we can remove all nulls from a List in Java.

Be the First to comment.

Published on Java Code Geeks with permission by Shubhra Srivastava, partner at our JCG program. See the original article here: Java – Remove all nulls from a List

Opinions expressed by Java Code Geeks contributors are their own.

Shubhra Srivastava

Shubhra is a software professional and founder of ProgrammerGirl. She has a great experience with Java/J2EE technologies and frameworks. She loves the amalgam of programming and coffee :)
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Ruurd
Ruurd
5 years ago

Maybe a better way is to prevent nulls to enter the collection in the first place. As an example of a list disallowing adding nulls as elements you can use PredicatedList from the Apache commons-collection4:

PredicatedList listWithoutNullElements = PredicatedList.predicatedList(new ArrayList(), NotNullPredicate.notNullPredicate());

Back to top button