Removing null Elements from a Java List – Techniques for Java 7, Java 8+, Apache Commons, Guava, and Groovy
This article demonstrates multiple ways to delete null entries from a Java List, covering Java 7's removeAll, Java 8's removeIf and stream filtering, as well as utility methods from Apache Commons, Google Guava, and a Groovy closure example.
The article explains how to remove null values from a List in different Java versions and with various libraries.
Java 7 or lower : Create a mutable list and call list.removeAll(Collections.singleton(null)); . Attempting the same on an immutable list throws java.lang.UnsupportedOperationException .
@Test
public void removeNull() {
List
list = new ArrayList<>(Arrays.asList("A", null, "B", null));
list.removeAll(Collections.singleton(null));
assertThat(list, hasSize(2));
}Java 8 or higher – using removeIf :
@Test
public void removeNull() {
List
list = new ArrayList<>(Arrays.asList("A", null, "B", null));
list.removeIf(Objects::isNull);
assertThat(list, hasSize(2));
}If you prefer to keep the original list unchanged, you can create a new list with streams:
@Test
public void removeNull() {
List
list = new ArrayList<>(Arrays.asList("A", null, "B", null));
List
newList = list.stream().filter(Objects::nonNull).collect(Collectors.toList());
assertThat(list, hasSize(4));
assertThat(newList, hasSize(2));
}Apache Commons Collections provides CollectionUtils.filter with a non‑null predicate:
@Test
public void removeNull() {
List
list = new ArrayList<>(Arrays.asList("A", null, "B", null));
CollectionUtils.filter(list, PredicateUtils.notNullPredicate());
assertThat(list, hasSize(2));
}Google Guava offers two approaches:
@Test
public void removeNull() {
List
list = new ArrayList<>(Arrays.asList("A", null, "B", null));
Iterables.removeIf(list, Predicates.isNull());
assertThat(list, hasSize(2));
}Or, to obtain a new list without modifying the original:
@Test
public void removeNull() {
List
list = new ArrayList<>(Arrays.asList("A", null, "B", null));
List
newList = new ArrayList<>(Iterables.filter(list, Predicates.notNull()));
assertThat(list, hasSize(4));
assertThat(newList, hasSize(2));
}Groovy solution using a closure:
List
list = new ArrayList<>(Arrays.asList("A", null, "B", null));
def re = list.findAll { it != null }
assert re == ["A", "B"]The article concludes with a disclaimer that the content is original and should not be republished without permission, followed by a curated list of other technical articles.
FunTester
10k followers, 1k articles | completely useless
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.