Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

November Discount Launch 2022 – Top
We’re finally running a Black Friday launch. All Courses are 30% off until tomorrow:


November Discount Launch 2022 – TEMP TOP (NPI)
We’re finally running a Black Friday launch. All Courses are 30% off until tomorrow:


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:

public void whenKeyIsPresent_thenContainsKeyReturnsTrue() {
    Map<String, String> map = Collections.singletonMap("key", "value");

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:

public void whenKeyHasNullValue_thenGetStillWorks() {
    Map<String, String> map = Collections.singletonMap("nothing", null);


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.

November Discount Launch 2022 – Bottom
We’re finally running a Black Friday launch. All Courses are 30% off until tomorrow:


Generic footer banner
Comments are closed on this article!