Apache Commons Collections - Ignore Null

Apache Commons Collections库的CollectionUtils类为常见操作提供了各种实用方法,涵盖了广泛的用例.它有助于避免编写样板代码.这个库在jdk 8之前非常有用,因为现在在Java 8的Stream API中提供了类似的功能.

检查非空元素

addIgnoreNull( )CollectionUtils的方法可用于确保只将非空值添加到集合中.

声明

以下是声明

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

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

参数

  • 集合 : 要添加的集合不得为null.

  • object : 要添加的对象,如果为null,则不会添加.

返回值

True如果集合发生了变化.

异常

  • NullPointerException : 如果集合为空.

示例

以下示例显示了org的用法. apache.commons.collections4.CollectionUtils.addIgnoreNull()方法.我们正在尝试添加空值和示例非空值.

import java.util.LinkedList;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;

public class CollectionUtilsTester {
   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");
      }
   } 
}

输出

它将打印以下内容结果.

[a]
Null value is not present