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

A'B :

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?

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=88398&siteId=1