Thuta Learning
Java
AdvancedProgrammingBeginner

HashMap

JavaLesson 2830 min

What you'll walk away with

  • Decide when to look things up by key with a Map instead of by index with a List
  • Predict that put replaces the value for an existing key and returns the old one, and that get returns null for a missing key
  • Count and group data with getOrDefault, merge and computeIfAbsent
  • Avoid relying on HashMap order and choose TreeMap or LinkedHashMap when order matters
  • Explain why key objects need correct equals/hashCode and should be immutable

Explain it simply

Explain it simply

Think of a HashMap as a dictionary: if you know the word (the key), you jump straight to its meaning (the value) without turning every page. A List is accessed by position, as in "the third item", while a Map is accessed by key, as in "the price of Mouse".

Each key has exactly one value, and putting the same key again replaces the old value. It is the right tool for any "I know this, find me that" data, such as username to role, product code to price, or country to capital city.

Problem → Why → Solution

The problem: scanning a list for every lookup

If you keep prices in two ArrayLists, one for names and one for prices, finding a product's price means scanning the name list from the start for its index and then reading the price list. With ten products you will not notice, but in a system that checks hundreds of thousands of orders this becomes very slow.

Keeping two lists in sync is also bug-prone: remove from one and forget the other, and prices end up attached to the wrong products. Searching for "mouse" in lowercase also misses "Mouse" and returns -1.

Main.java
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<String> names = List.of("Keyboard", "Mouse", "Monitor");
    List<Integer> prices = List.of(50, 25, 200);

    int index = names.indexOf("mouse");      // scans every name; case differs -> -1
    System.out.println(prices.get(index));   // IndexOutOfBoundsException
  }
}

What does HashMap change?

HashMap uses the key's hashCode() to compute directly which bucket to look in, so a lookup takes about the same time on average however big the map grows. The key and value live together in one entry, so there are no parallel lists to keep in sync. Keys are still compared exactly with equals(), though, so different letter case means a different key.

Core concept: from hash to bucket

Inside a HashMap is an array of buckets. When you call put(key, value), Java computes key.hashCode() and turns that number into a bucket index. get(key) recomputes the hash and looks in that one bucket only, which is why it stays fast on average even with a hundred thousand entries. Two different keys can land in the same bucket, which is called a collision, and then the entries in that bucket are compared one by one with equals().

That gives key classes one rule: two objects that are equal according to equals() must return the same hashCode(). String, Integer and records already follow this contract. If you use your own class as a key, override both equals() and hashCode() using the same fields; otherwise a lookup with an object that looks equal returns null. Changing a field used by the hash after the key is in the map also strands the entry in the wrong bucket, so it seems to vanish.

As entries pile up, HashMap rebuilds a bigger bucket array and redistributes the entries (default capacity 16, load factor 0.75). For this reason the specification does not guarantee any iteration order: it is neither insertion order nor alphabetical, and it can change after a resize. Use LinkedHashMap when you need insertion order and TreeMap when you need keys sorted.

HashMap accepts one null key and any number of null values. So when get() returns null you cannot tell "no such key" from "the key maps to null"; use containsKey() to tell them apart. HashMap is not thread-safe, so use ConcurrentHashMap when several threads modify a map at the same time.

Mental model: key to hash to bucket to equals
  1. Compute key.hashCode()
  2. Map the hash to one bucket
  3. Compare keys there with equals()
  4. Found: the value; missing: null

hashCode picks the bucket and equals picks the entry; both must be right for a lookup to work.

General pattern

java
Map<KeyType, ValueType> map = new HashMap<>();
map.put(key, value);                       // insert or replace
ValueType v = map.get(key);                // null when missing
ValueType d = map.getOrDefault(key, fallback);
boolean has = map.containsKey(key);
map.remove(key);
map.merge(key, 1, Integer::sum);           // counting
map.computeIfAbsent(key, k -> new ArrayList<>()).add(item); // grouping
for (Map.Entry<KeyType, ValueType> e : map.entrySet()) { use(e.getKey(), e.getValue()); }

Declare with the Map interface and create a HashMap. put inserts or replaces, get looks up (null when missing) and getOrDefault looks up with a fallback. merge is the usual tool for counting, computeIfAbsent for grouping into lists, and entrySet() loops over keys and values together.

Example: a product price map

This example stores product prices in a HashMap and shows what happens with a repeated key and a missing key. A HashMap does not guarantee any order, so printing it directly gives an order that depends on the JVM implementation. When the example prints the whole map, it copies it into a TreeMap sorted by key, so the output is the same on every machine.

Main.java
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class Main {
  public static void main(String[] args) {
    Map<String, Integer> prices = new HashMap<>();
    prices.put("Keyboard", 50);
    prices.put("Mouse", 25);
    prices.put("Monitor", 200);
    Integer old = prices.put("Mouse", 30);      // same key: value replaced

    System.out.println("Old mouse price: " + old);
    System.out.println("Mouse price: " + prices.get("Mouse"));
    System.out.println("Has Keyboard: " + prices.containsKey("Keyboard"));
    System.out.println("Webcam price: " + prices.get("Webcam"));
    System.out.println("Webcam or 0: " + prices.getOrDefault("Webcam", 0));
    System.out.println("Size: " + prices.size());
    System.out.println("Sorted: " + new TreeMap<>(prices));
  }
}

Code breakdown

  1. Line 7Map<String, Integer> prices = new HashMap<>();

    A map from String keys to Integer values. As with ArrayList, the type arguments must be reference types, so it is Integer, not int.

  2. Line 11Integer old = prices.put("Mouse", 30); // same key: value replaced

    "Mouse" already exists, so no new entry is added; 25 is replaced by 30. put() returns the old value 25, or null for a brand-new key, and the size stays at 3.

  3. Line 16System.out.println("Webcam price: " + prices.get("Webcam"));

    For a missing key, get() returns null rather than throwing. Writing int price = prices.get("Webcam"); would try to unbox null and throw NullPointerException.

  4. Line 17System.out.println("Webcam or 0: " + prices.getOrDefault("Webcam", 0));

    getOrDefault() returns the fallback 0 when the key is missing. It does not add anything to the map.

  5. Line 19System.out.println("Sorted: " + new TreeMap<>(prices));

    Copying the HashMap into a TreeMap prints the keys in alphabetical order. Reports and tests that print a map need a stable order like this.

You should see
Old mouse price: 25
Mouse price: 30
Has Keyboard: true
Webcam price: null
Webcam or 0: 0
Size: 3
Sorted: {Keyboard=50, Monitor=200, Mouse=30}

Counting with merge, grouping with computeIfAbsent

The two most common map jobs are counting and grouping. merge(key, 1, Integer::sum) stores 1 for a new key and otherwise adds 1 to the old value, so you no longer need an if/else around get and put. computeIfAbsent() creates and stores a new list when the key is missing and returns that list, so you can chain .add() directly.

Main.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class Main {
  public static void main(String[] args) {
    List<String> votes = List.of("tea", "coffee", "tea", "juice", "tea", "coffee");
    Map<String, Integer> counts = new HashMap<>();
    for (String vote : votes) {
      counts.merge(vote, 1, Integer::sum);       // 1 if new, else old + 1
    }
    System.out.println("Counts: " + new TreeMap<>(counts));

    List<String> names = List.of("Aye", "Bo", "Ann", "Chit", "Ben");
    Map<Character, List<String>> byLetter = new TreeMap<>();
    for (String name : names) {
      byLetter.computeIfAbsent(name.charAt(0), k -> new ArrayList<>()).add(name);
    }
    System.out.println("By letter: " + byLetter);

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

The output shows Counts: {coffee=2, juice=1, tea=3} and By letter: {A=[Aye, Ann], B=[Bo, Ben], C=[Chit]}. Names inside each group keep the order in which they were added to the list.

Key objects: records and the mutable-key trap

A record generates equals() and hashCode() from its components and its fields are final, which makes it ideal as a map key. The Tag class below has correct equals/hashCode, but its name field can still be changed. After name is changed while the tag sits in the map, neither the same object nor a new tag with the old name can find the entry, yet it is still stored.

Main.java
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class Main {
  static class Tag {
    String name;

    Tag(String name) {
      this.name = name;
    }

    @Override
    public boolean equals(Object o) {
      return o instanceof Tag other && name.equals(other.name);
    }

    @Override
    public int hashCode() {
      return Objects.hash(name);
    }
  }

  record Point(int x, int y) {}  // records get equals/hashCode for free

  public static void main(String[] args) {
    Map<Point, String> grid = new HashMap<>();
    grid.put(new Point(1, 2), "tree");
    System.out.println("Point lookup: " + grid.get(new Point(1, 2)));

    Map<Tag, Integer> usage = new HashMap<>();
    Tag tag = new Tag("java");
    usage.put(tag, 10);
    tag.name = "kotlin";                    // mutating a key after insertion
    System.out.println("Lookup by same object: " + usage.get(tag));
    System.out.println("Lookup by old name: " + usage.get(new Tag("java")));
    System.out.println("Entries still stored: " + usage.size());
  }
}

In real projects

Where this shows up in real projects

Maps appear everywhere in real applications. Load users from the database once, index them by id in a Map<Long, User>, and each order's customer can be found instantly without another query. Translation dictionaries from key to text, HTTP headers, feature-flag settings and in-memory caches of expensive results are all built on maps.

Report and analytics code counts orders per status with merge() and groups products by category with computeIfAbsent() every day. When producing JSON responses or comparing a test's expected output, teams do not trust HashMap order and use TreeMap or LinkedHashMap, so tests do not break when the JDK version changes. For caches that many threads write at once, such as in a web server, they pick ConcurrentHashMap.

Common mistakes

Common mistakes

1. Trusting HashMap's print order

The order of System.out.println(map) usually differs from insertion order and can change with the JDK version or capacity. A test that compares that output as a string will break one day. Use TreeMap or LinkedHashMap when order matters.

2. Assigning get() straight to an int

int stock = inventory.get("Webcam"); throws NullPointerException when the key is missing, because null cannot be unboxed. Use getOrDefault("Webcam", 0), or read it as an Integer and check for null.

3. Overriding equals() but forgetting hashCode()

Without a hashCode() override, two objects that are equal according to equals() usually get different default hash codes from Object, land in different buckets, and get() returns null. Write both using the same fields, or use a record.

4. Mutating a key after inserting it

Changing a field that feeds the hash strands the entry in its old bucket where no lookup will find it. Keep keys immutable.

Mini challenge

Mini challenge: a word counter

Count the words in a sentence ignoring case, then print the sorted counts, the number of unique words, the count for a present and a missing word, and the most frequent word.

  • countWords() lowercases the text and splits on anything that is not a letter
  • Count with merge(word, 1, Integer::sum)
  • Sort the counts with a TreeMap when printing
  • Show 0 for a missing word with getOrDefault
  • mostFrequent() breaks ties by choosing the alphabetically first word
Main.java
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class Main {
  static Map<String, Integer> countWords(String text) {
    Map<String, Integer> counts = new HashMap<>();
    // TODO: lowercase, split on non-letters, skip empty pieces, merge each word
    return counts;
  }

  static String mostFrequent(Map<String, Integer> counts) {
    // TODO: walk the entries in sorted key order and keep the highest count
    return null;
  }

  public static void main(String[] args) {
    String text = "The cat saw the dog. The dog saw a bird!";
    // TODO: print sorted counts, unique words, "the" and "fish" counts, most frequent
  }
}

Expected: The program should print: Counts: {a=1, bird=1, cat=1, dog=2, saw=2, the=3} Unique words: 6 the -> 3 fish -> 0 Most frequent: the

Show hint

split("[^a-z]+") splits on every run of characters outside a-z. To break ties alphabetically, loop over a TreeMap's entrySet() and replace best only when the count is strictly greater (use >, not >=).

Show solution
Main.java
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class Main {
  static Map<String, Integer> countWords(String text) {
    Map<String, Integer> counts = new HashMap<>();
    for (String word : text.toLowerCase().split("[^a-z]+")) {
      if (word.isEmpty()) {
        continue;
      }
      counts.merge(word, 1, Integer::sum);
    }
    return counts;
  }

  static String mostFrequent(Map<String, Integer> counts) {
    String best = null;
    for (Map.Entry<String, Integer> e : new TreeMap<>(counts).entrySet()) {
      if (best == null || e.getValue() > counts.get(best)) {
        best = e.getKey();
      }
    }
    return best;
  }

  public static void main(String[] args) {
    String text = "The cat saw the dog. The dog saw a bird!";
    Map<String, Integer> counts = countWords(text);
    System.out.println("Counts: " + new TreeMap<>(counts));
    System.out.println("Unique words: " + counts.size());
    System.out.println("the -> " + counts.getOrDefault("the", 0));
    System.out.println("fish -> " + counts.getOrDefault("fish", 0));
    System.out.println("Most frequent: " + mostFrequent(counts));
  }
}

Quick quiz 1 / 3

After Map<String, Integer> m = new HashMap<>(); m.put("a", 1); Integer r = m.put("a", 5);, what are r and m.size()?

Quick quiz 2 / 3

A non-record class Product is used as a key and overrides only equals(). What is likely to happen with map.get(new Product("A1"))?

Quick quiz 3 / 3

A report must show a map's keys in the order the user entered them. Which Map should you use?

What to remember

  • HashMap pairs each key with one value; hashCode picks the bucket and equals picks the entry, so lookups are fast on average.
  • put replaces the value for an existing key and get returns null when a key is missing; getOrDefault, merge and computeIfAbsent shorten common patterns.
  • Never rely on HashMap iteration order; use LinkedHashMap or TreeMap instead.
  • Keys need correct equals/hashCode and should be immutable, and a record is the easiest choice.

Java SE 25 API Specification — Oracle

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

HashMap | Thuta Learning