Member-only story
Filter Null Values in Java: Discussing 3 Options
Discussing 3 examples of filtering null values from Collections
2 min readMar 8, 2023
Originally Published in https://asyncq.com/
Introduction
- It's common to receive a collection where null values are included.
- The input collection that we received can contain null values in it.
1, 2, 3, 4, null, null
- It's not safe to operate on this ArrayList, we might get a null pointer exception.
- In this short article, Let’s quickly discuss what are the possible ways to filter null values from the ArrayList.
Option 1
- In this option, we create an additional result ArrayList, then iterate over the input array using for loop and compare for null on each element in the array.
List<Integer> integers = Arrays.asList(1, 2, 3, 4, null, null);
List<Integer> result = new ArrayList<>();
for(Integer val: integers){
if(val==null) continue;
result.add(val);
}
System.out.println("===> "+Arrays.toString(result.toArray()));
===> [1, 2, 3, 4]
Option 2
- Another option is to convert the list to streams API to get all the benefits of…