在Java中验证null和空集合的最佳实践

use*_*014 188 java collections

我想验证集合是否为空null.谁能告诉我最好的做法.

目前,我正在检查如下:

if (null == sampleMap || sampleMap.isEmpty()) {
  // do something
} 
else {
  // do something else
}
Run Code Online (Sandbox Code Playgroud)

Jal*_*ayn 282

如果在项目中使用Apache Commons Collections库,则可以使用CollectionUtils.isEmptyMapUtils.isEmpty()方法分别检查集合或映射是还是(即它们是"空值安全").

这些方法背后的代码或多或少是用户@icza在他的回答中所写的.

无论你做什么,记住你编写的代码越少,你需要测试的代码就越少,因为代码的复杂性会降低.

  • 可惜他们没有被命名为“ isNullOrEmpty”。 (11认同)
  • 感谢 MapUtils.isEmpty 是检查地图是否为空或空的完美解决方案 (2认同)

icz*_*cza 69

这是检查它的最佳方式.您可以编写辅助方法来执行此操作:

public static boolean isNullOrEmpty( final Collection< ? > c ) {
    return c == null || c.isEmpty();
}

public static boolean isNullOrEmpty( final Map< ?, ? > m ) {
    return m == null || m.isEmpty();
}
Run Code Online (Sandbox Code Playgroud)

  • @ismail`||'运算符是一个短路运算符,意味着如果左操作数是'true`,它将不会计算右操作数.因此,如果`m == null`,则不会调用`m.isEmpty()`(不需要,结果为`true`). (4认同)
  • 当然,您也可以为地图添加一张,但标题上注明了收藏。 (2认同)
  • 我不明白如果 m 为 null 那么 .isEmpty() 会导致 NullPointerException 吗?否则,如果左侧 (m==null) 为 true,则不会检查剩余部分 (2认同)

Nee*_*n.Z 29

如果您使用Spring框架,那么您可以使用它CollectionUtils来检查集合(列表,数组)和映射等.

if(CollectionUtils.isEmpty(...)) {...}
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句,spring 的 CollectionUtils 有评论...“杂项集合实用程序方法。主要用于框架内的内部使用。” 所以,我不确定是否使用这种方法:-) (3认同)

teh*_*exx 19

就个人而言,我更喜欢使用空集合而不是null算法,并且算法的工作方式对于算法而言,如果集合是空的,则无关紧要.


Mar*_*ari 8

您可以使用org.apache.commons.lang.ValidatenotEmpty ”方法:

Validate.notEmpty(myCollection)-> 验证指定的参数集合既不是 null 也不是大小为零(没有元素);否则抛出异常。


Dha*_*ama 7

当您使用弹簧时,您可以使用

boolean isNullOrEmpty = org.springframework.util.ObjectUtils.isEmpty(obj);
Run Code Online (Sandbox Code Playgroud)

其中obj是任何[map,collection,array,aythink ...]

否则:代码为:

public static boolean isEmpty(Object[] array) {
    return (array == null || array.length == 0);
}

public static boolean isEmpty(Object obj) {
    if (obj == null) {
        return true;
    }

    if (obj.getClass().isArray()) {
        return Array.getLength(obj) == 0;
    }
    if (obj instanceof CharSequence) {
        return ((CharSequence) obj).length() == 0;
    }
    if (obj instanceof Collection) {
        return ((Collection) obj).isEmpty();
    }
    if (obj instanceof Map) {
        return ((Map) obj).isEmpty();
    }

    // else
    return false;
}
Run Code Online (Sandbox Code Playgroud)

对于String最好的是:

boolean isNullOrEmpty = (str==null || str.trim().isEmpty());
Run Code Online (Sandbox Code Playgroud)


vik*_*ash 5

我们将检查 Collection 对象是否为空、是否为空。下面给出的所有这些方法都存在于 org.apache.commons.collections4.CollectionUtils 包中。

检查列表或设置集合对象的类型。

CollectionUtils.isEmpty(listObject);
CollectionUtils.isNotEmpty(listObject);
Run Code Online (Sandbox Code Playgroud)

检查对象的地图类型。

MapUtils.isEmpty(mapObject);
MapUtils.isNotEmpty(mapObject);
Run Code Online (Sandbox Code Playgroud)

所有方法的返回类型都是布尔值。