检查未知数量的集合和映射是否为空或为null

4

我正在尝试在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, mapOfStringToMap);
非常感谢您的帮助 :)

更新于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一样使用stream方法重载

如果你提到的util已经存在,那么你想要实现什么呢? - Himanshu Bhardwaj
你也可以只使用接受集合的方法,当你有一个映射时,将 myMap.keySet()myOtherMap.values() 传递给它。或者,你可以接收 Object... 并对可变参数数组中的每个对象使用 instanceof Collectioninstanceof Map,并委托给你发布的两种解决方案之一。缺点是你可以传递任何东西到这个方法中,即除了映射和集合之外,你还可以传递字符串、数字等。你应该处理这些情况... - fps
3个回答

2

您可以有两种不同的工具方法,一种用于检查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());
}

我也刚发现这个问题...谢谢,这就是原因,但我也想知道有没有更加“简洁”的方法来解决它? - Hearen
更简洁的方式?你能描述一下吗?我相信这很清楚。@Hearen - Ryuzaki L
使用一个 single 方法...看起来是不可能的。 - Hearen
1
在这种情况下是不可能的,因为您不能使用不同的流对象重载相同的方法,也不能在此处使用泛型 @Hearen - Ryuzaki L
为什么在读取所有空或null签名时要使用anyMatch为什么不用allMatch - Naman
我的意思是这只是一个例子,我会更新并使用@nullpointer。 - Ryuzaki L

2
不行。您无法创建一个与您寻找的通用性相同的对象,因为 Map 不是 Collection

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

唯一的方法是将它们拆分成两个单独的存根:

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);
}

1
你可以尝试这个:

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

问题不在于“stream”,而在于“参数”声明。 - Hearen
1
这个还不能处理Map - Naman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接