Key existence check in HashMap Key existence check in HashMap java java

Key existence check in HashMap


Do you ever store a null value? If not, you can just do:

Foo value = map.get(key);if (value != null) {    ...} else {    // No such key}

Otherwise, you could just check for existence if you get a null value returned:

Foo value = map.get(key);if (value != null) {    ...} else {    // Key might be present...    if (map.containsKey(key)) {       // Okay, there's a key but the value is null    } else {       // Definitely no such key    }}


You won't gain anything by checking that the key exists. This is the code of HashMap:

@Overridepublic boolean containsKey(Object key) {    Entry<K, V> m = getEntry(key);    return m != null;}@Overridepublic V get(Object key) {    Entry<K, V> m = getEntry(key);    if (m != null) {        return m.value;    }    return null;}

Just check if the return value for get() is different from null.

This is the HashMap source code.


Resources :


Better way is to use containsKey method of HashMap. Tomorrow somebody will add null to the Map. You should differentiate between key presence and key has null value.