Java Map Interface: HashMap, TreeMap and Methods like merge and compute (OCP 21)
Maps for the OCP 21 exam: HashMap, LinkedHashMap and TreeMap ordering, Map.of, ofEntries and copyOf, get, getOrDefault, put, putIfAbsent, replace, replaceAll, forEach and entrySet, plus the exact null rules of merge, compute, computeIfAbsent and computeIfPresent.
kvi5hnuCode Sprout team member9 min readOn this page
A Map stores key/value pairs and finds a value by its key: a phone book (name → number), a price list (product → price), a word counter (word → count). Keys are unique; values can repeat.
Map is part of the Collections Framework, but it does not extend Collection. It has no add, no contains and no iterator, and you can't put a map directly in an enhanced for loop. Keep that in mind: the exam regularly calls a Collection method on a map.
The three implementations
| Class | Order of keys | null key? | Lookup cost |
|---|---|---|---|
HashMap | none you can rely on (based on hashCode()) | one allowed | constant time on average |
LinkedHashMap | insertion order (or access order, optional) | one allowed | constant time on average |
TreeMap | sorted by the keys (natural order or a Comparator) | no with natural order: NullPointerException | grows with the log of the size |
All three allow null values. Putting an existing key again in a LinkedHashMap updates the value but does not move the key: its original position stays.
void fill(Map<String, Integer> stock) {
stock.put("plum", 12);
stock.put("date", 40);
stock.put("kiwi", 7);
System.out.println(stock.keySet());
}
fill(new LinkedHashMap<>()); // [plum, date, kiwi] insertion order
fill(new TreeMap<>()); // [date, kiwi, plum] sorted
fill(new HashMap<>()); // some order: never assume one
TreeMap sorts String keys by Unicode value, so digits come before uppercase letters, which come before lowercase letters: 10 < Apple < fig < pear. A TreeMap built with a Comparator (for example new TreeMap<>(Comparator.reverseOrder())) uses that order instead (article 56).
Creating maps with factory methods
Map<String, Integer> a = Map.of("plum", 3, "date", 9); // up to 10 key/value pairs
Map<String, Integer> b = Map.ofEntries(Map.entry("plum", 3), // any number of entries
Map.entry("date", 9));
Map<String, Integer> c = Map.copyOf(someMap); // snapshot of another map
Map.ofhas overloads for 0 to 10 pairs. Eleven pairs don't compile, and neither does a missing value (Map.of("a", 1, "b")).Map.ofEntriestakes a varargs ofMap.Entry. It's longer to type but impossible to misalign:Map.entry("a")doesn't compile.- All three return unmodifiable maps.
put,remove,replaceAll,mergeand the others throwUnsupportedOperationException. - No
nullanywhere. Anullkey or value throwsNullPointerException, and so doesMap.copyOfof a map holding anull. Evenget(null)andcontainsKey(null)throw on these maps. - A duplicate key in
Map.oforMap.ofEntriesthrowsIllegalArgumentExceptionat run time. - Iteration order is unspecified and can change between JVM runs, so never rely on it.
Map.entry(k, v) itself returns an immutable entry: setValue throws UnsupportedOperationException.
The methods to know
| Method | What it does |
|---|---|
V put(K key, V value) | adds or replaces; returns the previous value or null |
V get(Object key) | value for the key, or null if there's none |
V getOrDefault(Object key, V def) | value for the key, or def if the key is missing |
boolean containsKey(Object key) / containsValue(Object value) | membership test on keys / on values |
V remove(Object key) | removes the entry; returns the old value or null |
boolean remove(Object key, Object value) | removes only if the key currently maps to that value |
V putIfAbsent(K key, V value) | sets the value only if the key is missing or mapped to null |
V replace(K key, V value) | replaces only if the key is present; returns the old value |
boolean replace(K key, V oldValue, V newValue) | replaces only if the current value equals oldValue |
void replaceAll(BiFunction<K,V,V> f) | replaces every value with f(key, value) |
void forEach(BiConsumer<K,V> action) | runs action(key, value) for each entry |
Set<K> keySet() / Collection<V> values() / Set<Map.Entry<K,V>> entrySet() | views of keys, values and pairs |
int size() / boolean isEmpty() / void clear() | as in Collection |
merge, compute, computeIfAbsent, computeIfPresent | function-based updates, covered below |
Notice the parameter types: get, containsKey, containsValue and remove take Object, while put and the other update methods take K and V.
get versus getOrDefault
Map<Character, String> grades = new HashMap<>();
grades.put('A', "excellent");
System.out.println("A is " + grades.get('A')); // A is excellent
System.out.println("B is " + grades.get('B')); // B is null
System.out.println("B is " + grades.getOrDefault('B', "?")); // B is ?
getOrDefault returns the default only when the key is missing. If the key is present with a null value, it returns null, not the default.
Unboxing a missing value is a classic runtime trap: int n = counts.get("zzz"); compiles but throws NullPointerException.
put, putIfAbsent and replace
Map<String, String> seats = new HashMap<>();
seats.put("Ana", "A1");
seats.put("Raj", null);
System.out.println(seats.put("Ana", "B4")); // A1 (the old value)
seats.putIfAbsent("Ana", "C9"); // ignored: Ana has a non-null value
seats.putIfAbsent("Raj", "C9"); // set: a null value counts as absent
seats.putIfAbsent("Lee", "D2"); // added
System.out.println(seats.replace("Max", "E5")); // null, and Max is NOT added
seats.replaceAll((name, seat) -> name.charAt(0) + seat);
System.out.println(new TreeMap<>(seats)); // {Ana=AB4, Lee=LD2, Raj=RC9}
putalways writes.putIfAbsentwrites when the key is missing or mapped tonull. It returns the current value, ornullif it wrote.replacenever adds a key. It writes only when the key is already present, even when its value isnull.replaceAlltakes aBiFunction(key and value). A one-parameter lambda such asv -> v * 2doesn't compile.
Checking keys and values
System.out.println(seats.containsKey("Ana")); // true
System.out.println(seats.containsValue("Ana")); // false: values are seat codes
seats.contains("Ana"); // DOES NOT COMPILE: no contains on Map
seats.add("Zoe", "F1"); // DOES NOT COMPILE: it's put, not add
Iterating over a map
Three standard ways:
Map<String, Integer> stock = new TreeMap<>(Map.of("plum", 12, "date", 40));
stock.forEach((fruit, qty) -> System.out.println(fruit + " " + qty)); // BiConsumer: two parameters
for (String fruit : stock.keySet()) { ... } // keys only
stock.values().forEach(System.out::println); // values only
for (Map.Entry<String, Integer> e : stock.entrySet()) { // both, as entries
System.out.println(e.getKey() + " " + e.getValue());
}
Map.forEach takes a BiConsumer, so stock.forEach(k -> ...) doesn't compile. for (var e : stock) doesn't compile either, because a Map isn't Iterable.
The three views are live:
- Removing from
keySet()orvalues()(including withremoveIf) removes the entries from the map. - Calling
setValueon an entry fromentrySet()writes the new value into the map. - Views can't add:
keySet().add(...)throwsUnsupportedOperationException. - Changing the map's structure with
putorremovewhile you loop over a view usually throwsConcurrentModificationException, just as with lists.
merge and the compute methods
These four methods take a function and decide, based on the current state of the key, whether to call it. The rules are the most-tested part of Map:

merge(key, value, remappingFunction)
merge combines a new value with an existing one:
| Key state | Function called? | Result |
|---|---|---|
| missing | no | key added with value |
mapped to null | no | value set to value |
| mapped to a non-null value | yes: f(old, value) | result stored, or key removed if f returns null |
It returns the new value, or null if the key was removed. The value argument itself must not be null, or you get a NullPointerException.
Map<String, Integer> sales = new TreeMap<>();
for (String sold : List.of("plum", "kiwi", "plum", "date", "plum")) {
sales.merge(sold, 1, Integer::sum); // the counting idiom
}
System.out.println(sales); // {date=1, kiwi=1, plum=3}
BiFunction<String, String, String> longer = (oldV, newV) -> oldV.length() >= newV.length() ? oldV : newV;
Map<String, String> nick = new HashMap<>(Map.of("Ana", "Annie"));
nick.merge("Ana", "Anastasia", longer); // Anastasia (longer than Annie)
nick.merge("Raj", "R", longer); // R (key was missing: function not called)
nick.merge("Ana", "x", (o, n) -> null); // Ana removed
computeIfAbsent, computeIfPresent and compute
| Method | Calls the function when | Function receives | Function returns null |
|---|---|---|---|
computeIfAbsent(k, Function<K,V>) | key missing or mapped to null | the key | nothing is stored |
computeIfPresent(k, BiFunction<K,V,V>) | key mapped to a non-null value | key and old value | key is removed |
compute(k, BiFunction<K,V,V>) | always | key and old value (null if none) | key is removed (or not added) |
All three return the value now associated with the key, or null if there is none.
Map<Character, List<String>> byLetter = new TreeMap<>();
for (String fruit : List.of("pear", "plum", "date")) {
byLetter.computeIfAbsent(fruit.charAt(0), letter -> new ArrayList<>()).add(fruit);
}
System.out.println(byLetter); // {d=[date], p=[pear, plum]}
Map<String, Integer> visits = new HashMap<>();
visits.compute("home", (page, n) -> n == null ? 1 : n + 1); // 1
visits.compute("home", (page, n) -> n == null ? 1 : n + 1); // 2
visits.computeIfPresent("home", (page, n) -> null); // removes "home"
visits.computeIfPresent("about", (page, n) -> n + 1); // missing: nothing happens
computeIfAbsent(key, k -> new ArrayList<>()).add(...) is the standard multimap idiom: get the list for a key, creating it the first time.
Two more points:
- Count the lambda parameters.
computeIfAbsenttakes aFunctionwith one parameter. The other three take aBiFunctionwith two.computeIfAbsent("a", (k, v) -> 1)doesn't compile. - Don't modify the same map from inside the function.
HashMapdetects this and throwsConcurrentModificationException.
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
Hashtableis legacy. UseHashMap, orConcurrentHashMapwhen threads share the map (article 82).LinkedHashMapandSortedMapbecameSequencedMaps in Java 21 (article 57).
Exam traps from this article
A complete example
The program below compares map orders and exercises the factory methods, lookups, putIfAbsent, replace and replaceAll. It then counts with merge, groups with computeIfAbsent, removes entries by returning null, and finishes by writing through the live views.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class Solution {
static void fill(Map<String, Integer> stock) {
stock.put("plum", 12);
stock.put("date", 40);
stock.put("kiwi", 7);
}
public static void main(String[] args) {
// 1. Same puts, three iteration orders
Map<String, Integer> linked = new LinkedHashMap<>();
Map<String, Integer> tree = new TreeMap<>();
fill(linked);
fill(tree);
System.out.println("LinkedHashMap: " + linked.keySet()); // insertion order
System.out.println("TreeMap: " + tree.keySet()); // sorted keys
// 2. Immutable factories
Map<String, Integer> prices = Map.ofEntries(
Map.entry("plum", 3),
Map.entry("date", 9));
try {
prices.put("kiwi", 4);
} catch (UnsupportedOperationException e) {
System.out.println("Map.ofEntries result is unmodifiable");
}
// 3. Basic lookups and return values
Map<String, Integer> stock = new HashMap<>(linked);
System.out.println("put returns old value: " + stock.put("kiwi", 9));
System.out.println("get missing: " + stock.get("lime")
+ ", getOrDefault missing: " + stock.getOrDefault("lime", 0));
stock.put("lime", null); // HashMap allows null values
System.out.println("getOrDefault on null-mapped key: " + stock.getOrDefault("lime", 0));
System.out.println("putIfAbsent fills the null: " + stock.putIfAbsent("lime", 5)
+ " -> " + stock.get("lime"));
System.out.println("replace on missing key: " + stock.replace("fig", 1)
+ ", containsKey(fig): " + stock.containsKey("fig"));
// 4. replaceAll gets key and value
stock.replaceAll((fruit, qty) -> fruit.equals("date") ? qty - 10 : qty);
System.out.println("after replaceAll: " + new TreeMap<>(stock));
// 5. merge: counting and the null-result removal rule
Map<String, Integer> sales = new TreeMap<>();
for (String sold : List.of("plum", "kiwi", "plum", "date", "plum")) {
sales.merge(sold, 1, Integer::sum);
}
System.out.println("sales: " + sales);
sales.merge("kiwi", 1, (oldQty, one) -> oldQty - one == 0 ? null : oldQty - one);
System.out.println("kiwi merged to null is removed: " + sales);
// 6. compute family
Map<Character, List<String>> byLetter = new TreeMap<>();
for (String fruit : List.of("pear", "plum", "date", "kiwi", "peach")) {
byLetter.computeIfAbsent(fruit.charAt(0), letter -> new ArrayList<>()).add(fruit);
}
System.out.println("grouped: " + byLetter);
byLetter.computeIfPresent('k', (letter, list) -> null); // null removes the entry
byLetter.compute('d', (letter, list) -> list == null ? null : List.of(list.size() + " item"));
System.out.println("after compute: " + byLetter);
// 7. Iterating: forEach(BiConsumer) and entrySet()
StringBuilder line = new StringBuilder();
tree.forEach((fruit, qty) -> line.append(fruit).append('=').append(qty).append(' '));
System.out.println("forEach: " + line.toString().trim());
int total = 0;
for (Map.Entry<String, Integer> e : tree.entrySet()) {
e.setValue(e.getValue() * 2); // writes through to the map
total += e.getValue();
}
System.out.println("doubled: " + tree + ", total " + total);
// 8. Views are live
tree.keySet().remove("date");
tree.values().removeIf(qty -> qty < 20);
System.out.println("after view removals: " + tree);
}
}
Output:
LinkedHashMap: [plum, date, kiwi]
TreeMap: [date, kiwi, plum]
Map.ofEntries result is unmodifiable
put returns old value: 7
get missing: null, getOrDefault missing: 0
getOrDefault on null-mapped key: null
putIfAbsent fills the null: null -> 5
replace on missing key: null, containsKey(fig): false
after replaceAll: {date=30, kiwi=9, lime=5, plum=12}
sales: {date=1, kiwi=1, plum=3}
kiwi merged to null is removed: {date=1, plum=3}
grouped: {d=[date], k=[kiwi], p=[pear, plum, peach]}
after compute: {d=[1 item], p=[pear, plum, peach]}
forEach: date=40 kiwi=7 plum=12
doubled: {date=80, kiwi=14, plum=24}, total 118
after view removals: {plum=24}
Points to notice:
put("kiwi", 9)returned7, the value it replaced.getOrDefault("lime", 0)returned0whilelimewas missing, butnulloncelimewas mapped tonull.putIfAbsentthen treated thatnullas absent and stored5.replace("fig", 1)didn't addfig.- The
mergethat computed0 → nullremovedkiwifrom the sales map, andcomputeIfPresentreturningnullremoved thekgroup. e.setValue(...)in theentrySet()loop changed the map itself, and removing throughkeySet()andvalues()removed real entries.
Common questions
Why doesn't Map extend Collection?
A collection is a group of single elements, but a map holds pairs. Methods like add(E) don't fit. The views (keySet, values, entrySet) are how a map becomes a collection when you need one.
Should I use getOrDefault or containsKey plus get?
Use getOrDefault when a missing value has a natural default, such as 0 for a count. For counting itself, merge(key, 1, Integer::sum) is shorter still.
Which map should I choose?
Use HashMap by default. Use LinkedHashMap when output must follow insertion order (or, with access order, for a simple LRU cache). Use TreeMap when you need keys sorted or range queries such as "first key after X".
Is Map.Entry a class?
It's a nested interface. The entries you get from entrySet() are live views. Map.entry(k, v) and, since Java 17, Map.Entry.copyOf(e) create unmodifiable stand-alone entries.
Summary
HashMaphas no order,LinkedHashMapkeeps insertion order, andTreeMapsorts keys and rejects anullkey under natural ordering.Map.of(≤10 pairs),Map.ofEntriesandMap.copyOfcreate unmodifiable, null-free maps.putreturns the old value,getOrDefaultcovers missing keys,putIfAbsentalso fillsnullvalues, andreplacenever adds.- Iterate with
forEach((k, v) -> …),keySet(),values()orentrySet(). The views are live. mergeand thecomputemethods call their functions only in specific key states, and anullresult removes the key or adds nothing.
Practice quiz
Test yourself with the Map interface quiz: 10 exam-style questions with explanations.
Previous: Java Set, Queue and Deque: HashSet, TreeSet, ArrayDeque and Their Methods (OCP 21)
Next: Java Sorting: Comparable, Comparator, Collections.sort and binarySearch (OCP 21)
Related reading
- Java Set, Queue and Deque: HashSet, TreeSet, ArrayDeque and Their Methods (OCP 21)
- Java List Interface: ArrayList, LinkedList, Factory Methods and List Operations (OCP 21)
- Java Collections Framework: The Collection Interface and Common Methods (OCP 21)
- Java Variable Scope and Garbage Collection (OCP 21)
- Java Legacy Collections: Hashtable, Enumeration, Properties, Stack and BitSet

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.