VOOZH about

URL: https://www.javacodegeeks.com/2019/03/java-remove-nulls-from-list.html

⇱ Java – Remove all nulls from a List - Java Code Geeks


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.

Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Thank you!

We will contact you soon.

👁 Photo of Shubhra Srivastava
Shubhra Srivastava
March 19th, 2019Last Updated: March 18th, 2019
1 4,445 2 minutes read

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

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

1 Comment
Oldest
Newest Most Voted
Ruurd
7 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());

3
Reply
Back to top button
Close
wpDiscuz