首页 > 解决方案 > 检查 EmptyOrNull 以获取未知数量的集合和地图

问题描述

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

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

所以我可以处理以下情况:

任何帮助将不胜感激:)

更新于 2018 年 12 月 6 日

感谢@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;
}

当然,你可以像nullpointerstream一样使用and 。method overloading

标签: javadictionarycollectionsjava-8

解决方案


您可以有两种不同的 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());
}

推荐阅读