HashMap
Java programming
contains method
get method
coding best practices

HashMap - contains and get methods should not be used together

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

A common Java HashMap pattern looks like this:

java
if (map.containsKey(key)) {
    return map.get(key);
}

People often call this inefficient because it performs two lookups. That criticism is usually fair, but the full rule is more precise: do not call containsKey and then get unless you actually need to distinguish between a missing key and a key mapped to null.

Why The Double Lookup Is Usually Unnecessary

If null is not a meaningful stored value, one get call is enough:

java
1String value = map.get(key);
2if (value != null) {
3    return value;
4}

This avoids hashing and bucket lookup twice. It is also shorter and easier to read.

For a HashMap, that may still be average-case constant time either way, but it is still unnecessary work and unnecessary code.

When containsKey Is Actually Needed

The important exception is null. HashMap.get returns null in two different cases:

  • the key is absent
  • the key is present and mapped to null

If your map allows null values and that distinction matters, then containsKey is the correct additional check:

java
if (map.containsKey(key)) {
    return map.get(key);  // may legitimately be null
}

In that situation, the double lookup is not just defensible. It is logically necessary unless you redesign the map usage.

Better Alternatives In Modern Java

Sometimes the real issue is not lookup style but missing intent. Modern Map APIs often express that intent better:

java
String value = map.getOrDefault(key, "fallback");

Or when computing missing values:

java
String value = map.computeIfAbsent(key, k -> loadValue(k));

These methods make the code clearer than manually mixing containsKey and get in many everyday cases.

Readability Matters Too

Even if the performance difference is small, duplicate lookups are often a readability smell because they suggest the programmer is working around uncertainty about the API. Good map code usually answers one of these questions directly:

  • give me the value if it exists
  • tell me whether the key exists
  • give me a fallback if missing
  • compute a value if missing

Once you know which question you are asking, the right method becomes clearer.

One Lookup Is Not Always The Whole Story

This advice is really about intent, not micro-optimization for its own sake. If your map design forbids null values, one get is both faster and clearer. If null is meaningful, the extra presence check reflects correct business logic rather than waste.

null Changes The Recommendation

That single detail is what makes the blanket rule too simplistic.

Common Pitfalls

  • Using containsKey and get together when null values are impossible or irrelevant.
  • Using get alone when null is a valid stored value and presence must be distinguished from absence.
  • Replacing the pair with containsValue, which answers a different question entirely.
  • Ignoring more expressive methods such as getOrDefault and computeIfAbsent.
  • Treating the advice as an absolute rule instead of a rule with a specific null-handling exception.

Summary

  • 'containsKey plus get often means two lookups where one would do.'
  • If null is not a valid stored value, a single get is usually enough.
  • If null is meaningful, containsKey may be necessary to distinguish presence from absence.
  • Modern Map methods often express intent more clearly than manual checks.
  • The best rule is not "never combine them," but "combine them only when the semantics require it."

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.