This quick tutorial is going to show how to remove all null elements
from a List, using plain Java, Guava, the Apache Commons Collections and
the newer Java 8 lambda support.
3. Remove nulls from a List using Apache Commons Collections
Let’s now look at a simple solution using the Apache Commons Collections library using a similar functional style:
4. Remove nulls from a List using Lambdas (Java 8)
Finally – let’s look at a Java 8 solution using Lambdas to filter the List; the filtering process can be done in parallel or serial:
1. Remove nulls from a List using plain Java
The Java Collections Framework offers a simple solution for removing all null elements in the List – a basic while loop:@Test
public void givenListContainsNulls_whenRemovingNullsWithPlainJava_thenCorrect() {
List<Integer> list = Lists.newArrayList(null, 1, null);
while (list.remove(null));
assertThat(list, hasSize(1));
}
Note that this approach will modify the source list.2. Remove nulls from a List using Google Guava
We can also remove nulls using Guava and a more functional approach, via predicates:@Test
public void givenListContainsNulls_whenRemovingNullsWithGuavaV1_thenCorrect() {
List<Integer> list = Lists.newArrayList(null, 1, null);
Iterables.removeIf(list, Predicates.isNull());
assertThat(list, hasSize(1));
}
Alternatively, if we don’t want to modify the source list, Guava will allow us to create a new, filter list:@Test
public void givenListContainsNulls_whenRemovingNullsWithGuavaV2_thenCorrect() {
List<Integer> list = Lists.newArrayList(null, 1, null, 2, 3);
List<Integer> listWithoutNulls = Lists.newArrayList(
Iterables.filter(list, Predicates.notNull()));
assertThat(listWithoutNulls, hasSize(3));
}
3. Remove nulls from a List using Apache Commons Collections
Let’s now look at a simple solution using the Apache Commons Collections library using a similar functional style:private void removeNullsFromListApache() {
List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
CollectionUtils.filter(list, PredicateUtils.notNullPredicate());
}
Note that this solution will also create a new list and leave the original unchanged.
4. Remove nulls from a List using Lambdas (Java 8)
Finally – let’s look at a Java 8 solution using Lambdas to filter the List; the filtering process can be done in parallel or serial:public void givenListContainsNulls_whenFilteringParallel_thenCorrect() {
List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
List<Integer> listWithoutNulls =
list.parallelStream().filter(i -> i != null).collect(Collectors.toList());
}
public void givenListContainsNulls_whenFilteringSerial_thenCorrect() {
List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
List<Integer> listWithoutNulls =
list.stream().filter(i -> i != null).collect(Collectors.toList());
}
And that’s it – some quick and very useful solutions for getting rid of all null elements from a List.
Useful info.Keep it up :)
ReplyDelete