如何检查集合不为空且集合中的元素也不为空

Dol*_*hin 1 java

我在 java 8 中使用 apache collections utils 得到的是 null:

if (CollectionUtils.isNotEmpty(reportEnvelopeApps)) {

}
Run Code Online (Sandbox Code Playgroud)

但是如果集合 reportEnvelopeApps 包含一个元素 null,它会意外地工作。所以我必须写这样的代码:

        if (reportEnvelopeApps == null) {
            return null;
        }
        reportEnvelopeApps.removeAll(Collections.singleton(null));
        if (CollectionUtils.isEmpty(reportEnvelopeApps)) {
            return null;
        }
Run Code Online (Sandbox Code Playgroud)

避免此类不良代码的更好方法是什么?

Dea*_*ool 5

您可以使用Optional和返回仅包含非空元素的列表,否则返回null

List<String> res = Optional.ofNullable(reportEnvelopeApps)
            .map(list->list.removeIf(Objects::isNull) ? list : list)
            .filter(list->!list.isEmpty())
            .orElse(null);
Run Code Online (Sandbox Code Playgroud)