Skip to content
Tutorials Center
My learning

Topics

Lesson 82 of 201 ยท Collections

HashMap

Learn Java HashMap - put, get, getOrDefault and putIfAbsent, iterating entries, merge, compute and computeIfAbsent, plus counting and grouping recipes.

A HashMap stores key-value pairs and finds the value for a key almost instantly, no matter how many entries it holds. Prices by product code, users by email, word counts by word, settings by name: whenever your program asks "what goes with this?", a map is the answer, and HashMap is the default map.

This lesson covers the complete everyday API: adding and reading entries, the right way to handle missing keys, iterating, and the powerful merge, compute and computeIfAbsent methods that turn counting and grouping into one-liners. The next lesson, How HashMap Works Inside, opens the hood.

Creating a map and basic operations

Map<K, V> has two type parameters: the key type and the value type. Keys are unique; values can repeat.

Java put, get, remove and friends

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The core methods:

Method Does Returns
put(k, v) add or replace previous value, or null
get(k) look up value, or null if absent
getOrDefault(k, d) look up with a fallback value, or d
containsKey(k) key test (fast) boolean
containsValue(v) value test (scans everything) boolean
remove(k) / remove(k, v) remove (the second only if mapped to v) old value / boolean
putIfAbsent(k, v) add only if missing existing value, or null
replace(k, v) replace only if present previous value, or null
size(), isEmpty(), clear()

You can also build small maps with Map.of("a", 1, "b", 2) (up to 10 pairs) or Map.ofEntries(Map.entry("a", 1), ...). Those are immutable; wrap them in new HashMap<>(...) to get a modifiable copy.

Missing keys

get returns null for a missing key, and that null is the source of many bugs. Unboxing it into an int throws a NullPointerException (Wrapper Classes). Prefer methods that say what should happen when the key isn't there:

Java
int stock = inventory.getOrDefault("pens", 0);       // fallback value
inventory.putIfAbsent("pens", 0);                    // initialize once
if (inventory.containsKey("pens")) { ... }           // explicit test

HashMap also allows one null key and any number of null values. That makes get(k) == null ambiguous: is the key missing, or mapped to null? Only containsKey can tell. The simplest rule is to never store null values in a map at all. (Map.of, TreeMap with natural ordering and ConcurrentHashMap reject null keys anyway.)

Iterating over a map

A map isn't a Collection, but it offers three collection views:

  • keySet(): a Set of keys.
  • values(): a Collection of values (may contain duplicates).
  • entrySet(): a Set of Map.Entry<K, V> pairs, each with getKey(), getValue() and setValue().
Java Looping over keys, values and entries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Iterate over entrySet() when you need both key and value. Looping over keySet() and calling get(key) inside does a second lookup for every key, which is slower and noisier.

Two rules about iteration:

  • Order is not defined. HashMap order depends on hash codes and capacity, can change when the map grows, and differs between Java versions. Never rely on it. Use LinkedHashMap for insertion order or TreeMap for sorted keys (LinkedHashMap and LinkedHashSet, TreeMap and TreeSet). The example prints the result through new TreeMap<>(scores) to get alphabetical order.
  • Don't call map.put or map.remove inside a loop over the map. Structural changes during iteration throw ConcurrentModificationException. Use removeIf on a view, the iterator's remove(), setValue or replaceAll, all of which are safe.

Views are live: removing a key from keySet() removes the entry from the map.

merge: counting made easy

Counting things is the classic map task. The old way needs an if:

Java
if (counts.containsKey(word)) {
    counts.put(word, counts.get(word) + 1);
} else {
    counts.put(word, 1);
}

merge(key, value, function) does it in one call: if the key is absent, it stores value; if present, it stores function(oldValue, value). If the function returns null, the entry is removed.

Java Word frequencies with merge

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Change the text in the Input box and run it again. Integer::sum is a method reference for (a, b) -> a + b. To show results sorted by count, sort a stream of entries; the map itself stays unordered.

computeIfAbsent: grouping

To group items into lists, you need "get the list for this key, creating it if necessary". computeIfAbsent(key, k -> new ArrayList<>()) returns the existing value, or computes, stores and returns a new one, so you can chain .add(...) straight onto it:

Java Grouping with computeIfAbsent, updating with compute

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The four "compute-style" methods side by side:

Method Runs the function when Function receives Returning null
computeIfAbsent(k, f) key is absent (or mapped to null) the key stores nothing
computeIfPresent(k, f) key is present key and old value removes the entry
compute(k, f) always key and old value (or null) removes the entry
merge(k, v, f) key present: combine; absent: just store v old value and v removes the entry

A common mistake is writing computeIfAbsent(key, k -> new ArrayList<>()).add(x) and then put-ing the list back; there's no need, since the list stored in the map is the same object you just added to. Another is modifying the same map from inside the function, which is forbidden and may throw ConcurrentModificationException.

Streams can do the same grouping declaratively with Collectors.groupingBy (Collecting Stream Results). Use whichever reads better; for loops that also do other work, computeIfAbsent is often simpler.

Choosing good keys

A HashMap finds keys with hashCode() and confirms them with equals(). So:

  • Keys must implement equals and hashCode consistently. String, wrapper classes, enums and records do. A plain class without overrides compares by identity, so a new-but-equal key never finds anything (The Object Class).
  • Keys must not change while in the map. If a field used by hashCode changes, the entry is effectively lost. Prefer immutable keys.
  • For composite keys, use a record rather than gluing strings together (city + ":" + year breaks as soon as a city name contains a colon):
Java Records make safe composite keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The record key works because records generate equals and hashCode from their components. The plain class doesn't override them, so two objects with the same city are still different keys, and the lookup returns null. How HashMap Works Inside shows exactly why, and what happens to mutable keys.

Performance and limits

  • Average O(1) for put, get, remove and containsKey, independent of the map's size, as long as keys have well-distributed hash codes.
  • containsValue is O(n): values aren't indexed. If you search by value often, keep a second map in the opposite direction.
  • Pre-size large maps. HashMap.newHashMap(10_000) (Java 19+) creates a map that holds 10,000 entries without resizing. The older new HashMap<>(10_000) sets the capacity, which isn't the same thing, as the next lesson explains.
  • Not thread-safe. Concurrent writes can corrupt a HashMap. Use ConcurrentHashMap across threads (Concurrent Collections).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? Map<String, Integer> m = new HashMap<>(); m.put("a", 1); System.out.println(m.put("a", 2));

    put replaces the value for an existing key and returns the previous value, which was 1.
  2. 2. After counts.merge("x", 1, Integer::sum) runs three times on an empty map, what is counts.get("x")?

    The first merge stores 1 because the key is absent. The next two combine the old value with 1 using Integer::sum, giving 2 and then 3.
  3. 3. Which line correctly adds "pen" to a list stored under key "bo" in a Map<String, List<String>>, creating the list if needed?

    computeIfAbsent returns the existing list or stores and returns a new one. get throws NullPointerException for a new key, put replaces existing items, and putIfAbsent returns null when it inserts.
  4. 4. You loop over map.keySet() and call map.remove(key) for some keys. What is the likely result?

    Removing through the map during iteration is a structural change the iterator detects. Use map.keySet().removeIf(...) or the iterator's remove() instead.
  5. 5. Why does get(new PlainKey("Lima")) return null when PlainKey doesn't override equals and hashCode?

    Without overrides, Object's identity-based equals and hashCode are used. Records, Strings and wrappers compare by value, which is what map keys need.

Summary

  • HashMap<K, V> maps unique keys to values with average O(1) put, get, remove and containsKey.
  • put returns the old value; get returns null for missing keys, so prefer getOrDefault, putIfAbsent or containsKey.
  • Iterate with entrySet() or forEach((k, v) -> ...); remove with removeIf on a view; never rely on HashMap order.
  • merge handles counting and summing, computeIfAbsent handles grouping, compute/computeIfPresent update or remove based on the old value.
  • Keys need consistent equals and hashCode and must not change while in the map; records are ideal composite keys.
  • Avoid null values, pre-size big maps with HashMap.newHashMap(n), and use ConcurrentHashMap across threads.

Next: How HashMap Works Inside, where you'll see hashing, buckets, collisions and resizing in action.