Remove null elements from a List in Java

1). Removing all null elements in the List using while loop

The Java Collections Framework provides different ways to remove the null elements from the list.

<Integer> list = Lists.newArrayList(11,22,null, 33, null); while (list.remove(null));

or We can have

<Integer> list = Lists.newArrayList(151,122,11,22,null, 33, null); list.removeAll(Collections.singleton(null));

2). Using Apache Commons Collections

The Apache Commons Collections library has CollectionUtils class contains filter method,which removes null from the given list.

List<Integer> list = Lists.newArrayList(151,122,11,22,null, 33, null); CollectionUtils.filter(list, PredicateUtils.notNullPredicate());

3). Using Lambdas from Java 8

The lambdas in java has filtering mechanism usong which we can remove null from list.

List<Integer> list = Lists.newArrayList(151,122,11,22,null, 33, null); List<Integer> listWithoutNulls = list.parallelStream() .filter(Objects::nonNull) .collect(Collectors.toList());

In this article, we have seen Remove null elements from a List in Java.