Berk U.
Berk U.

Reputation: 7198

Java: given a HashMap, how can I use containsKey() to tell if key is explicitly mapped to a null value?

I am currently learning Java and running into some trouble with simple Java code where I have to deal with a HashMap that has missing keys and values.

Specifically, I am looking for an way to distinguish between the following two cases given a HashMap myHashMap:

  1. myHashMap.get("myKey") is explicitly mapped to null
  2. myHashMap does not contain an key for "myKey"

In looking around for a solution, I found the following in documentation for the get method for HashMaps in Java 8 SE, which says that:

A return value of null does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to null. The containsKey operation may be used to distinguish these two cases.

I am wondering if someone knows how I could use containsKey() in this way?

Upvotes: 0

Views: 74

Answers (4)

QHuy
QHuy

Reputation: 51

Yes you can use the contain key method

http://www.javaworld.com/article/2073473/java-map-get-and-map-containskey.html

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 122026

1) myHashMap.get("myKey") is explicitly mapped to null

Even though it mapped to null, still containsKey return true for you because there is a key called myKey exists holding a value null

2)myHashMap does not contain an key for "myKey"

That obviously return false, Since no key found with that name.

Upvotes: 1

ruakh
ruakh

Reputation: 183602

You can distinguish the three possibilities (not mapped to anything vs. explicitly mapped to null vs. mapped to a non-null value) like this:

final boolean keyIsNotMappedToAnything =
    !myHashMap.containsKey("myKey");

final boolean keyIsExplicitlyMappedToNull =
    myHashMap.containsKey("myKey") && myHashMap.get("myKey") == null;

final boolean keyIsMappedToANonNullValue =
    myHashMap.get("myKey") != null;

Upvotes: 0

djechlin
djechlin

Reputation: 60848

There's not much more to explain, but here's an explicit code sample.

HashMap<Integer, Object> m = new HashMap<>();
m.put(1, new Object());
m.containsKey(1); // returns true
m.containsKey(2); // returns false

Upvotes: 0

Related Questions