Hearen
Hearen

Reputation: 7828

check EmptyOrNull for unknown amount of collections and maps

I am trying to achieve an util as this in Spring Boot:

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

so I can handle cases as:

Any help will be sincerely appreciated :)

Updated 2018-12-06

Thanks for the help of @Deadpool, my solution turns out:

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

Of course, you can use stream and method overloading as nullpointer does.

Upvotes: 4

Views: 108

Answers (3)

Ryuzaki L
Ryuzaki L

Reputation: 39978

You can have two different util methods one for to check Collection objects and another one for Map objects, since Map is not child of Collection interface

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

To check all objects null or empty

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

Upvotes: 2

Naman
Naman

Reputation: 31858

No. You cannot create it as generic as you are looking for since a Map is not a Collection.

And of course Collection... collectionList signifies var args for Collection type.

The only way would be to break them into two separate stubs as :

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

Upvotes: 2

Bahramdun Adil
Bahramdun Adil

Reputation: 6079

You can try this:

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

Upvotes: 1

Related Questions