HashMap in Java: How It Works and How to Use It

admin5 min read
In this tutorial
  1. Creating a map and adding entries
  2. Reading values safely
  3. Updating values: merge, compute and putIfAbsent
  4. Removing entries
  5. Iterating over a map
  6. How HashMap works inside
  7. Why equals and hashCode matter
  8. Choosing the right Map
  9. Summary

When you need to find something by a key (a user by email, a price by product code, a count by word), a HashMap is usually the right tool. It finds values in roughly constant time no matter how big the map gets.

This tutorial covers everyday HashMap usage, the modern helper methods that make your code shorter, and how a hash map actually works inside, which is a very common interview topic.

Creating a map and adding entries

A map stores key-value pairs. Each key appears at most once.

import java.util.HashMap;
import java.util.Map;

Map<String, Integer> stock = new HashMap<>();
stock.put("rice", 40);
stock.put("beans", 25);
stock.put("garri", 60);
stock.put("rice", 35);   // same key: replaces 40 with 35

System.out.println(stock.get("rice"));   // 35
System.out.println(stock.size());        // 3

As with lists, declare the variable as the Map interface. For a small fixed map you can also write Map.of("a", 1, "b", 2), which is immutable.

Reading values safely

get returns null when the key is missing, which leads straight to NullPointerException if you are not careful:

int yam = stock.get("yam");   // NullPointerException when unboxing null

Safer options:

int yam = stock.getOrDefault("yam", 0);        // 0 if missing
boolean hasBeans = stock.containsKey("beans"); // true

Updating values: merge, compute and putIfAbsent

These methods replace a lot of clumsy if (map.containsKey(...)) code.

Counting word frequency is the classic example:

import java.util.HashMap;
import java.util.Map;

public class WordCount {
    public static void main(String[] args) {
        String text = "java is fun and java is powerful and java is everywhere";
        Map<String, Integer> counts = new HashMap<>();

        for (String word : text.split(" ")) {
            counts.merge(word, 1, Integer::sum);
        }

        System.out.println(counts.get("java")); // 3
        System.out.println(counts.get("is"));   // 3
        System.out.println(counts.get("fun"));  // 1
    }
}

merge(key, 1, Integer::sum) means: if the key is missing, store 1; otherwise store oldValue + 1.

Other useful methods:

stock.putIfAbsent("yam", 10);                       // only adds if missing
stock.computeIfAbsent("plantain", k -> 0);          // compute a default lazily
stock.computeIfPresent("rice", (k, v) -> v - 5);    // update only if present

computeIfAbsent is perfect for grouping values into lists:

Map<String, List<String>> byCity = new HashMap<>();
byCity.computeIfAbsent("Lagos", k -> new ArrayList<>()).add("Ada");
byCity.computeIfAbsent("Lagos", k -> new ArrayList<>()).add("Tunde");
byCity.computeIfAbsent("Abuja", k -> new ArrayList<>()).add("Fatima");
// {Lagos=[Ada, Tunde], Abuja=[Fatima]}

Removing entries

stock.remove("garri");             // remove by key
stock.remove("beans", 99);         // only removes if the value matches
stock.entrySet().removeIf(e -> e.getValue() == 0); // remove all out-of-stock items

Iterating over a map

Loop over entrySet() when you need both key and value. It is more efficient than looping over keys and calling get each time:

for (Map.Entry<String, Integer> e : stock.entrySet()) {
    System.out.println(e.getKey() + " -> " + e.getValue());
}

stock.forEach((item, qty) -> System.out.println(item + ": " + qty));

Important: HashMap does not keep any order. The output order may look random and can change between Java versions. If you need insertion order, use LinkedHashMap. If you need keys sorted, use TreeMap.

How HashMap works inside

Here is what happens when you call map.put("rice", 35):

  1. Java calls "rice".hashCode() to get an int.
  2. It mixes the bits of that hash and uses it to pick a bucket, a slot in an internal array.
  3. If the bucket is empty, the entry goes there.
  4. If the bucket already holds entries (a collision), Java walks through them, comparing keys with equals(). If it finds an equal key, it replaces the value; otherwise it adds a new entry to the bucket.

get follows the same steps: hash the key, find the bucket, then use equals() to find the exact entry. Because the bucket is found directly from the hash, lookups take about the same time whether the map holds ten entries or ten million.

A few more details interviewers like:

  • Load factor and resizing. By default the internal array starts with 16 buckets and doubles when the map is 75% full (load factor 0.75). Resizing re-distributes every entry, so if you know you will store 10,000 items, creating the map with a larger initial capacity avoids repeated resizing.
  • Treeification. Since Java 8, when one bucket gets too crowded (more than 8 entries, in a table of at least 64 buckets), its entries are stored as a balanced tree. This limits the worst case to O(log n) instead of O(n).
  • Null keys. HashMap allows one null key and many null values. Hashtable and ConcurrentHashMap allow neither.

Why equals and hashCode matter

If you use your own class as a key, it must override both equals and hashCode consistently:

import java.util.HashMap;
import java.util.Map;

public class KeyDemo {
    static class BadKey {
        final String code;
        BadKey(String code) { this.code = code; }
        // no equals/hashCode!
    }

    record GoodKey(String code) { }   // records generate equals and hashCode

    public static void main(String[] args) {
        Map<BadKey, Integer> bad = new HashMap<>();
        bad.put(new BadKey("A1"), 100);
        System.out.println(bad.get(new BadKey("A1")));   // null: different hash, different object

        Map<GoodKey, Integer> good = new HashMap<>();
        good.put(new GoodKey("A1"), 100);
        System.out.println(good.get(new GoodKey("A1"))); // 100
    }
}

The rules:

  • If a.equals(b) is true, a.hashCode() must equal b.hashCode().
  • Never change a field used in hashCode while the object is a key in a map. The entry will be stuck in the wrong bucket and become unreachable. Immutable keys (like String and records) avoid this problem completely.

Choosing the right Map

  • HashMap: fastest general-purpose map, no ordering.
  • LinkedHashMap: keeps insertion order (or access order, which is useful for LRU caches).
  • TreeMap: keeps keys sorted, and offers firstKey, floorKey, headMap and so on. Operations are O(log n).
  • ConcurrentHashMap: safe for many threads at once, without locking the whole map.

Summary

  • HashMap stores key-value pairs with near-constant-time lookups.
  • Use getOrDefault, merge and computeIfAbsent instead of manual null checks.
  • Iterate over entrySet(), and do not rely on HashMap ordering.
  • Inside, keys are hashed into buckets and matched with equals(), so key classes need correct equals and hashCode.

Next: process collections in a few readable lines with Java Streams.

Ask a question or leave a comment

Your email address will not be published. Required fields are marked *