繁体   English   中英

检查Map不包含空键和值

[英]Check Map not to contain null keys and values

现在我有这个丑陋的代码来检查一个hashmap是否包含空键和值。 是否已准备好使用具有相同功能的Guava静态方法?

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

并不是的。

Preconditions.checkNotNull

你可能应该使用它。 令人惊讶的是,它比你的简单检查更快(它被优化以更好地内联常见情况,即不抛出)。 它抛出NPE而不是IAE

还有MapConstraint ,AFAIK允许您创建这样的Map。

并且还有许多类不允许null ,例如, ImmutableMap 理论上你可以做到

ImmutableMap.copyOf(map)

但这将不必要地创建一个副本。

如果你可以从一开始就使用ImmutableMap,也许是通过它的Builder,你会在尝试插入一个空键或值时出现错误。 所以这可能值得一看。

这很简单:

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

亲:您不必捕获任何NPE。

Con:在最坏的情况下,你必须迭代整个地图。 两次。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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