Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 879
A'B Avatar asked Dec 01 '25 22:12

A'B


2 Answers

boolean hasAnyNull = yourMap.keySet()
      .stream()
      .anyMatch(Objects::isNull);
like image 52
Eugene Avatar answered Dec 04 '25 10:12

Eugene


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.

like image 34
Joachim Sauer Avatar answered Dec 04 '25 12:12

Joachim Sauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!