How do I test null keys on any Java map implementation?

I want to make sure that the map passed to the method as a parameter does not contain a null key People will think that the following situations will:

if ( map.containsKey(null) ) …

However, if the method passed is similar to treemap, it will be broken. According to the general Java map contract, it is free to reject null keys with a NPE

Do we have a reasonable way to test null keys while accepting any map implementation?

Solution

boolean hasAnyNull = yourMap.keySet()
boolean hasAnyNull = yourMap.keySet()
      .stream()
      .anyMatch(Objects::isNull);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>