1. Overview
In this brief tutorial, we’ll look at ways to check if a key exists in a Map.
Specifically, we’ll focus on containsKey and get.
2. containsKey
If we take a look at the JavaDoc for Map#containsKey:
Returns true if this map contains a mapping for the specified key
We can see that this method is a pretty good candidate for doing what we want.
Let’s create a very simple map and verify its contents with containsKey:
@Test
public void whenKeyIsPresent_thenContainsKeyReturnsTrue() {
Map<String, String> map = Collections.singletonMap("key", "value");
assertTrue(map.containsKey("key"));
assertFalse(map.containsKey("missing"));
}
Simply put, containsKey tells us whether the map contains that key.
3. get
Now, get can sometimes work, too, but it comes with some baggage, depending on whether or not the Map implementation supports null values.
Again, taking a look at Map‘s JavaDoc, this time for Map#put, we see that it will only throw a NullPointerException:
if the specified key or value is null and this map does not permit null keys or values
Since some implementations of Map can have null values (like HashMap), it’s possible for get to return null even though the key is present.
So, if our goal is to see whether or not a key has a value, then get will work:
@Test
public void whenKeyHasNullValue_thenGetStillWorks() {
Map<String, String> map = Collections.singletonMap("nothing", null);
assertTrue(map.containsKey("nothing"));
assertNull(map.get("nothing"));
}
But, if we are just trying to check that the key exists, then we should stick with containsKey.
4. Conclusion
In this article, we looked at containsKey. We also took a closer look at why it’s risky to use get for verifying a key’s existence.
As always, check out the code examples over on Github.