Commons Collections 简明教程

Apache Commons Collections - Ignore Null

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

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

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

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

Declaration

以下是声明:

Following is the declaration for

org.apache.commons.collections4.CollectionUtils.addIgnoreNull() 方法 −

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

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

Parameters

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

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

Return Value

如果集合发生更改,则返回 True。

True if the collection changed.

Exception

  1. NullPointerException − If the collection is null.

Example

以下示例显示 org.apache.commons.collections4.CollectionUtils.addIgnoreNull() 方法的用法。我们尝试添加一个 null 值和一个非 null 值示例。

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

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

输出如下:

The output is mentioned below −

[a]
Null value is not present