繁体   English   中英

如何检查列表中的列表是否为空?

[英]How check if the lists in a list are not empty?

我有一个Java列表。 这是代码:

List<List<Integer>> myList = new ArrayList<>();
myList.add(new ArrayList<Integer>());
myList.add(new ArrayList<Integer>());
myList.add(new ArrayList<Integer>());

myList.get(0).add(1);
myList.get(0).add(2);
myList.get(0).add(3);
myList.get(1).add(4);
myList.get(1).add(5);
myList.get(1).add(6);
myList.get(2).add(7);
myList.get(2).add(8);
myList.get(2).add(9);

现在在我的代码的一部分中,我想检查位于myList中的所有三个列表是否都为空且为空。 我应该逐个检查这些列表中的每一个,如下所示:

if (myList.get(0) != null && !myList.get(0).isEmpty()) { 
    // do something
} 

......还是有更好更短的方法而不是一个一个地检查?

您可以为此使用流API,也可以使用普通循环:

 boolean allNonEmptyOrNull = myList.stream()
     .allMatch(x -> x != null && !x.isEmpty());

或者您可以检查是否包含null或空List ,例如,通过:

System.out.println(myList.contains(null) || myList.contains(Collections.<Integer> emptyList()));

但是最后一个选项将打破Java 9不可变集合,例如:

List.of(1, 2, 3).contains(null); 

将抛出NullPointerException

使用Java 7及更低版本,这是接近它的经典方法:

for (List<Integer> list : myList) {
    if (list != null && !list.isEmpty()) {
        // do something with not empty list
    }
}

使用Java 8及更高版本,您可以使用forEach

myList.forEach(list -> {
    if (list != null && !list.isEmpty()) {
        // do something with not empty list
    }
});

或者,正如Eugene已经提到的 ,使用流API,您可以使用lambda-expression替换if语句:

myList.stream()
      .filter(list -> (list != null && !list.isEmpty()))
      .forEach(list -> {
          // do something with not empty list
      });

注意:所有这三个示例都暗示您已初始化myList变量并且它不为null ,否则将在上面的所有片段中抛出NullPointerException

标准JDK没有快速检查集合是否为空且不为空的方法。 但是如果你使用的是Apache commons-collections库,它们提供了这样一个方法: CollectionUtils.isNotEmpty() 但是,我不建议仅为了这个单一功能而将此依赖项添加到项目中。

你可以这样做:

boolean isEmpty = false;
for(List<Integer> list : myList) {
   if(list == null || list.isEmpty()) {
      isEmpty = true;
      break;
   }
}

if(!isEmpty) { // do your thing; }

只检查您的收藏不包含空列表

if (!L.contains(Collections.EMPTY_LIST)){ do something }

或者空和空检查(小心NullPointerException !!!)

if (!L.contains(Collections.EMPTY_LIST) && !L.contains(null)){ do something }
int temp = 0;
for(int i=0;i<L.size();i++) {
    if (L.get(i).isEmpty()) {
        temp++;
    }
}
if (temp == L.size()) {
   //do what you want, all the lists inside L are empty
}

这就是我现在所能想到的。

我会使用Java foreach循环。 它类似于索引循环,但读取更好,并且更短。

boolean nonempty = true;

for (List<Integer> list : myList) {
    if (list == null || list.isEmpty()) {
        nonempty = false;
        break;
    }
}

如果您找到一个空列表,这也可以让您早点爆发。

我想检查列表中的所有三个列表是否都不为空

myList.stream().anyMatch(List::isEmpty);

如果任何内部列表为空,则应该输出一个输出。 根据您的要求,您可以否定它。
但是如果你还需要检查null ,那么你可以尝试一下,

myList.stream().anyMatch(i -> null==i || i.isEmpty())

你可以再次根据需要否定。 这个答案是为上述答案添加变体。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM