How to test for null keys on any Java map implementation?

寵の児 提交于 2019-12-23 15:44:14

问题


I would like to ensure that a Map being passed as an argument to a method doesn't include null keys. One would assume that the following would do:

if ( map.containsKey(null) ) …

but that will break if the method is passed something like a TreeMap, which per the general Java Map contract is free to reject null keys with a NPE.

Do we have a sensible way to test for null keys while accepting any Map implementation?


回答1:


boolean hasAnyNull = yourMap.keySet()
      .stream()
      .anyMatch(Objects::isNull);



回答2:


boolean hasNullKey(Map<?,?> map) {
  try {
    return map.containsKey(null);
  } catch (NullPointerException e) {
    return false;
  }
}

Note that this also returns false when map itself is null, which may or may not be desired.




回答3:


Use instanceof to find its a TreeMap

boolean hasNullKey(Map<?,?> map) {
    return map instanceof TreeMap ? false :map.containsKey(null);
}


来源:https://stackoverflow.com/questions/52275537/how-to-test-for-null-keys-on-any-java-map-implementation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!