Apache Commons Collections - 忽略空值



Apache Commons Collections 庫的 CollectionUtils 類提供了多種實用方法用於通用操作,覆蓋了廣泛的用例。它有助於避免編寫樣板程式碼。此庫在 jdk 8 之前非常有用,因為類似的功能現在在 Java 8 的 Stream API 中提供。

檢查非空元素

CollectionUtils 的 addIgnoreNull() 方法可用於確保僅將非空值新增到集合中。

宣告

以下是對

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

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

引數

  • 集合 − 要新增到的集合,不得為 null。

  • 物件 − 要新增的物件,如果為 null,則不會新增。

返回值

如果集合已更改,則返回 True。

異常

  • NullPointerException − 如果集合為 null。

示例

以下示例顯示了 org.apache.commons.collections4.CollectionUtils.addIgnoreNull() 方法的用法。我們嘗試新增一個 null 值和一個示例非 null 值。

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
廣告