请检查EmptyOrNull以获取未知数量的集合和映射



我正试图在Spring Boot:中实现这样的util

public static boolean isAllEmptyOrNull(Collection... collectionList) {
for (Collection collection : collectionList) {
if (!Collections.isEmpty(collection)) {
return false;
}
}
return true;
}

这样我就可以处理以下情况:

  • isAllEmptyOrNull(listOfCat(
  • isAllEmptyOrNull(listOfDog,mapOfStringToString(
  • isAllEmptyOrNull(listOfDog,listOfCat(
  • isAllEmptyOrNull(listOfDog、listOfCat、mapOfStringToList、mapOfString ToMap(

如有任何帮助,我们将不胜感激:(

更新时间:2018-12-06

感谢@Deadpool的帮助,我的解决方案是:

public static boolean isAllCollectionEmptyOrNull(Collection... collections) {
for (Collection collection : collections) {
if (!Collections.isEmpty(collection)) {
return false;
}
}
return true;
}
public static boolean isAllMapEmptyOrNull(Map... maps) {
for (Map map : maps) {
if (!Collections.isEmpty(map)) {
return false;
}
}
return true;
}

当然,您可以像使用nullpointer一样使用streammethod overloading

。由于Map不是Collection,因此无法将其创建为所需的泛型。

当然,Collection... collectionList表示Collection类型的var参数。

唯一的方法是将它们分成两个独立的存根,如下所示:

public static boolean isAllEmptyOrNull(Collection... collectionList) {
return Arrays.stream(collectionList).allMatch(Collection::isEmpty);
}
public static boolean isAllEmptyOrNull(Map... maps) {
return Arrays.stream(maps).allMatch(Map::isEmpty);
}

您可以有两种不同的util方法,一种用于检查Collection对象,另一种用于Map对象,因为Map不是Collection接口的子级

public static boolean isAllEmptyOrNull(Collection... collectionList) {
return Arrays.stream(collectionList).anyMatch(item->item==null || item.isEmpty());
}
public static boolean isAllEmptyOrNull(Map... maps) {
return Arrays.stream(maps).anyMatch(item->item==null || item.isEmpty());
}

检查所有对象nullempty

public static boolean isAllEmptyOrNull(Collection... collectionList) {
return Arrays.stream(collectionList).allMatch(item->item==null || item.isEmpty());
}
public static boolean isAllEmptyOrNull(Map... maps) {
return Arrays.stream(maps).allMatch(item->item==null || item.isEmpty());
}

你可以试试这个:

public static boolean isAllEmptyOrNull(Collection... collectionList) {
return Arrays.stream(collectionList).anyMatch(Collection::isEmpty);
}

最新更新