目录

安全空检查(Safe Empty Checks)

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

检查非空列表

CollectionUtils的isNotEmpty()方法可用于检查列表是否为空而不必担心空列表。 因此,在检查列表大小之前,不需要将null检查放在任何地方。

声明 (Declaration)

以下是声明

org.apache.commons.collections4.CollectionUtils.isNotEmpty()方法

public static boolean isNotEmpty(Collection<?> coll)

参数 (Parameters)

  • coll - 要检查的集合,可以为null。

返回值 (Return Value)

如果非null且非空,则为True。

例子 (Example)

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

输出 (Output)

它将打印以下结果。

Non-Empty List Check: false
Non-Empty List Check: false

检查空列表

CollectionUtils的isEmpty()方法可用于检查列表是否为空而不必担心空列表。 因此,在检查列表大小之前,不需要将null检查放在任何地方。

声明 (Declaration)

以下是声明

org.apache.commons.collections4.CollectionUtils.isEmpty()方法 -

public static boolean isEmpty(Collection<?> coll)

参数 (Parameters)

  • coll - 要检查的集合,可以为null。

返回值 (Return Value)

如果为空或为空,则为真。

例子 (Example)

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

输出 (Output)

它将打印以下结果。

Empty List Check: true
Empty List Check: true
↑回到顶部↑
WIKI教程 @2018