[英]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.