简体   繁体   中英

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

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, ie, not throwing). It throws NPE instead of IAE .

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

And there are also many classes not allowing null s, eg, ImmutableMap . In theory you could do

ImmutableMap.copyOf(map)

but this would needlessly create a copy.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM