Contents

Remove null from a list in Java

Written by: David Vlijmincx
Contents

Introduction

This quick will show how to remove all null values from a list in Java using plain Java in three different ways.

RemoveIf() to remove all null values from a list

With Java 8 and higher, we can use the removeIf method to remove nulls from the fruits list. RemoveIf alters the original list, meaning it will remove the null values from the list of the fruit.

1
2
3
4
5
6
7
8
9
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add(null);
fruits.add("Banana");
fruits.add(null);

fruits.removeIf(Objects::isNull);

assertEquals(fruits.size(), 2);

Remove() to remove all nulls from a list

We use a while loop in the following example to remove null values from the fruits list. The while loop will run until it has removed all the null values individually.

1
2
3
4
5
6
7
8
9
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add(null);
fruits.add("Banana");
fruits.add(null);

while (fruits.remove(null));

assertEquals(fruits.size(), 2);

filter() to remove all nulls from a list

With Java 8, we can also use streams to create a list without the null values. Using stream will not alter the original list but create a copy of the list without the null values.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add(null);
fruits.add("Banana");
fruits.add(null);

List<String> listWithoutNull = fruits
        .stream()
        .filter(Objects::nonNull)
        .collect(Collectors.toList());

assertEquals(listWithoutNull.size(), 2);

Conclusion

In this article, we showed how to remove null values using streams, List.removeIf(), and a for-loop.