
- Commons Collections 教程
- Commons Collections - 首頁
- Commons Collections - 概述
- Commons Collections - 環境設定
- Commons Collections - Bag 介面
- Commons Collections - BidiMap 介面
- Commons Collections - MapIterator 介面
- Commons Collections - OrderedMap 介面
- Commons Collections - 忽略空值
- Commons Collections - 合併與排序
- Commons Collections - 物件轉換
- Commons Collections - 物件過濾
- Commons Collections - 安全的空檢查
- Commons Collections - 包含
- Commons Collections - 交集
- Commons Collections - 差集
- Commons Collections - 並集
- Commons Collections 資源
- Commons Collections - 快速指南
- Commons Collections - 有用資源
- Commons Collections - 討論
Commons Collections - 安全的空檢查
Apache Commons Collections 庫的 CollectionUtils 類提供了各種實用方法,用於涵蓋廣泛用例的常見操作。它有助於避免編寫樣板程式碼。在 Java 8 的 Stream API 提供類似功能之前,此庫在 jdk 8 之前非常有用。
檢查非空列表
CollectionUtils 的 isNotEmpty() 方法可用於檢查列表是否非空,而無需擔心空列表。因此,在檢查列表大小之前,無需在所有地方都放置空檢查。
宣告
以下是
org.apache.commons.collections4.CollectionUtils.isNotEmpty() 方法的宣告 -
public static boolean isNotEmpty(Collection<?> coll)
引數
coll - 要檢查的集合,可能為 null。
返回值
如果非空且非 null,則返回 true。
示例
以下示例顯示了org.apache.commons.collections4.CollectionUtils.isNotEmpty() 方法的使用。我們將檢查列表是否為空。
import java.util.List; import org.apache.commons.collections4.CollectionUtils; public class CollectionUtilsTester { public static void main(String[] args) { List<String> list = getList(); System.out.println("Non-Empty List Check: " + checkNotEmpty1(list)); System.out.println("Non-Empty List Check: " + checkNotEmpty1(list)); } static List<String> getList() { return null; } static boolean checkNotEmpty1(List<String> list) { return !(list == null || list.isEmpty()); } static boolean checkNotEmpty2(List<String> list) { return CollectionUtils.isNotEmpty(list); } }
輸出
輸出如下所示 -
Non-Empty List Check: false Non-Empty List Check: false
檢查空列表
CollectionUtils 的 isEmpty() 方法可用於檢查列表是否為空,而無需擔心空列表。因此,在檢查列表大小之前,無需在所有地方都放置空檢查。
宣告
以下是
org.apache.commons.collections4.CollectionUtils.isEmpty() 方法 -
public static boolean isEmpty(Collection<?> coll)
引數
coll - 要檢查的集合,可能為 null。
返回值
如果為空或 null,則返回 true。
示例
以下示例顯示了org.apache.commons.collections4.CollectionUtils.isEmpty() 方法的使用。我們將檢查列表是否為空。
import java.util.List; import org.apache.commons.collections4.CollectionUtils; public class CollectionUtilsTester { public static void main(String[] args) { List<String> list = getList(); System.out.println("Empty List Check: " + checkEmpty1(list)); System.out.println("Empty List Check: " + checkEmpty1(list)); } static List<String> getList() { return null; } static boolean checkEmpty1(List<String> list) { return (list == null || list.isEmpty()); } static boolean checkEmpty2(List<String> list) { return CollectionUtils.isEmpty(list); } }
輸出
以下是程式碼的輸出 -
Empty List Check: true Empty List Check: true
廣告