目录

Commons Collections - Ignore NULL

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

检查非空元素

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

声明 (Declaration)

以下是声明

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

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

参数 (Parameters)

  • collection - 要添加的集合,不能为null。

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

返回值 (Return Value)

如果收集更改,则为True。

异常 (Exception)

  • NullPointerException - 如果集合为null。

例子 (Example)

以下示例显示了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");
      }
   }
}

输出 (Output)

它将打印以下结果。

[a]
Null value is not present
↑回到顶部↑
WIKI教程 @2018