Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • isAllEmptyOrNull(listOfCat);
  • isAllEmptyOrNull(listOfDog, mapOfStringToString);
  • isAllEmptyOrNull(listOfDog, listOfCat);
  • isAllEmptyOrNull(listOfDog, listOfCat, mapOfStringToList, mapOfStringToMap);

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.

like image 789
Hearen Avatar asked Sep 07 '25 14:09

Hearen


2 Answers

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);
}
like image 197
Naman Avatar answered Sep 09 '25 08:09

Naman


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());
}
like image 33
Deadpool Avatar answered Sep 09 '25 07:09

Deadpool