Apache Commons Collections - Ignore Null



Overview

CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8's Stream API.

Check for Not Null Elements

addIgnoreNull() method of CollectionUtils can be used to ensure that only non-null values are getting added to the collection.

Usage

a = "a";
b = null;
CollectionUtils.addIgnoreNull(list, a);
CollectionUtils.addIgnoreNull(list, b); // b being null will not be added.

Declaration

Following is the declaration for

org.apache.commons.collections4.CollectionUtils.addIgnoreNull() method −

public static <T> boolean addIgnoreNull(Collection<T> collection, T object)

Parameters

  • collection − The collection to add to, must not be null.

  • object − The object to add, if null it will not be added.

Return Value

True if the collection changed.

Exception

  • NullPointerException − If the collection is null.

Example - Usage of addIgnoreNull() method to ignore null values

The following example shows the usage of addIgnoreNull() method. We are trying to add a null value and a sample non-null value.

CommonCollectionsTester.java

package com.tutorialspoint;

import java.util.LinkedList;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;

public class CommonCollectionsTester {
   public static void main(String[] args) {
      List<String> list = new LinkedList<String>();
      CollectionUtils.addIgnoreNull(list, null);
      CollectionUtils.addIgnoreNull(list, "a");

      System.out.println(list);

      if(list.contains(null)) {
         System.out.println("Null value is present");
      } else {
         System.out.println("Null value is not present");
      }
   }
}

Output

The output is mentioned below −

[a]
Null value is not present
Advertisements