Reputation: 1973
I need to check if all values in a map are null, I have this method that I want to replace by a built-in one if possible. Limitations: Java 5 and access to Apache Commons libraries.
/* Checks if all values are null */
public static boolean isEmpty(Map<Dboid,?> aMap){
boolean isEmpty = true;
Iterator<?> it = aMap.entrySet().iterator();
while(it.hasNext() && isEmpty){
Object value = it.next();
if(value != null) {
isEmpty = false;
}
}
return isEmpty;
}
Upvotes: 3
Views: 25068
Reputation: 1582
I know the question is for Java 5, but for those who will come here from google search as I did:
For Java >= 8 you can do:
boolean allValuesAreNull = yourMap.values()
.stream()
.allMatch(Objects::isNull);
with one nuance: it will be true
for empty map.
Upvotes: 16
Reputation: 1374
There is no API that will give you that, however you could optimize that method a little bit.
No need to check the isEmpty variable on every iteration.
That is a minor optimization.
/* Checks if all values are null */
public static <K,V> boolean isMapEmpty(Map<K,V> aMap){
for (V v: aMap.values()) {
if (v != null) { return false; }
}
return true;
}
Upvotes: 1
Reputation: 29959
Another solution without using any third party libraries.
Collections.frequency(aMap.values(), null) == aMap.size()
Upvotes: 8
Reputation: 213233
As such there is no direct method for this, but you can use Apache Commons CollectionUtils.countMatches()
method, and pass a NullPredicate
instance to it. Of course, you would do pass the values in the map using Map#values()
method:
public static <K, V> boolean hasAllNullValues(Map<K, V> map) {
int size = map.size();
return CollectionUtils.countMatches(map.values(), NullPredicate.INSTANCE) == size;
}
or even better, use CollectionUtils.exists()
method, to check there is at least one element that satisfies the NotNullPredicate
passed as second argument:
public static <K, V> boolean hasAllNullValues(Map<K, V> map) {
return !CollectionUtils.exists(map.values(), NotNullPredicate.INSTANCE);
}
Upvotes: 4
Reputation: 2597
how about
return CollectionUtils.find(aMap.values(),NotNullPredicate.INSTANCE).isEmpty();
Upvotes: 2
Reputation: 40335
There is no built-in method to do this. In particular, there's nothing that provides a means of "finding an element that isn't equal to something".
However, if a map that contains only null
values is defined by your business rules to be "empty", that seems to imply that null
values mean "not present", in which case you may wish to construct the code such that null
values are never added in the first place. Then you can just use the built in isEmpty()
.
Upvotes: 2