Filter Null Values in Java: Discussing 3 Options

  • Post last modified:March 19, 2023
  • Reading time:2 mins read

Discussing 3 examples of filtering null values from Collections

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 functional style coding.
  • We use a method reference to filter nonnull elements and then finally convert it to result in array.
        List<Integer> integers = Arrays.asList(1, 2, 3, 4, null, null);
        var x = integers
                .stream()
                .filter(Objects::nonNull) // method reference
                .toArray();
         
===> [1, 2, 3, 4]

Option 3

  • This option is my favorite. We can write a lambda Function block that takes a stream as an input and then output the stream.
  • In the logic part, we can use our method reference for nonNull check.
Function<Stream<Integer>, Stream<Integer>> compact = (stream) -> 
                                          stream.filter(Objects::nonNull);
  • Now we can use this code block and apply it on any input stream and get the nonnull stream out of it
       List<Integer> integers1 = Arrays.asList(1, 2, 3, null);
       Stream<Integer> integers1C = compact.apply(integers1.stream());
       System.out.println(Arrays.toString(integers1C.toArray()));

====>[1, 2, 3]

Conclusion

  • In this article, we discuss 3 options to filter null values from a list in Java.

Leave a Reply