A'B
A'B

Reputation: 535

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?

Upvotes: 3

Views: 420

Answers (3)

gifpif
gifpif

Reputation: 4917

Use instanceof to find its a TreeMap

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

Upvotes: 0

Joachim Sauer
Joachim Sauer

Reputation: 308001

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.

Upvotes: 1

Eugene
Eugene

Reputation: 120848

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

Upvotes: 5

Related Questions