Nikolay Kuznetsov
Nikolay Kuznetsov

Reputation: 9579

Check Map not to contain null keys and values

For now I have this ugly code to check whether a hashmap contains null keys and values. Is there ready to use Guava static method with same functionality?

    if (map != null) {
        // Check map does not contains null key
        try {
            if (map.containsKey(null)) {
                throw new IllegalArgumentException("map contains null as key");
            }
        } catch (NullPointerException e) {
            //It is ok. Map does not permit null key.
        }

        // Check map does not contains null key
        try {
            if (map.containsValue(null)) {
                throw new IllegalArgumentException("map contains null price");
            }
        } catch (NullPointerException e) {
            //It is ok. Map does not permit null value.
        }
    }

Upvotes: 0

Views: 5474

Answers (3)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298898

This is simple enough:

public static <K,V>boolean containsNullKeysOrValues(Map<K,V> map){
    return containsNullKeys(map)|| containsNullValues(map);
}
public static <K, V> boolean containsNullKeys(Map<K, V> map) {
    return Iterables.tryFind(map.keySet(), Predicates.isNull()).isPresent();
}
public static <K, V> boolean containsNullValues(Map<K, V> map) {
    return Iterables.tryFind(map.values(), Predicates.isNull()).isPresent();
}

Pro: You don't have to catch any NPEs.

Con: In the worst case you have to iterate the entire map. Twice.

Upvotes: 0

isomeme
isomeme

Reputation: 471

If you can use an ImmutableMap from the beginning, perhaps via its Builder, you'd get an error as soon as you tried to insert a null key or value. So that might be worth a look.

Upvotes: 0

maaartinus
maaartinus

Reputation: 46422

Not really. There's

Preconditions.checkNotNull

which you should probably use. Surprisingly, it's faster than your simple check (it's optimized for better inlining of the common case, i.e., not throwing). It throws NPE instead of IAE.

There are also MapConstraints, which AFAIK would allow you to create such a Map.

And there are also many classes not allowing nulls, e.g., ImmutableMap. In theory you could do

ImmutableMap.copyOf(map)

but this would needlessly create a copy.

Upvotes: 1

Related Questions