Java Maps: HashMap, TreeMap and Updating Map Entries
A practical guide to Java's Map interface: HashMap versus TreeMap, put, get and getOrDefault, iterating with forEach, and updating entries the modern way with merge, compute, computeIfAbsent and putIfAbsent. Includes word counting, multimaps, and the null-value pitfalls.
kvi5hnuCode Sprout team member10 min readOn this page
A set answers "is this element here?", but only if you already have a copy of the element. Most lookups don't work that way. You have some key, such as an employee ID, a username or a word, and you want the data that belongs to it. That is what a map is for. A map stores key/value pairs and finds the value for a key quickly. Maps are probably the most heavily used data structure in real Java code, so this article covers them thoroughly: choosing an implementation, the basic operations, and the update methods that make code like word counting a one-liner.
HashMap or TreeMap?
The two general-purpose implementations of the Map interface mirror the two sets you met in article 85:
HashMaphashes the keys into buckets.get,putandremoveare O(1) on average, and iteration order is unspecified.TreeMapkeeps the keys in a red-black tree, sorted by their natural order or by aComparator. Operations are O(log n), and iteration visits the keys in sorted order.
Only the keys are hashed or compared. Values are simply carried along, so they need no hashCode or compareTo. Everything from article 85 applies to keys: equals and hashCode must agree, a TreeMap comparator must be consistent with equals, and you must never mutate a key while it is in a map.
The rule of thumb is the same as for sets. Use HashMap unless you need sorted keys or range queries.
Basic operations
var staff = new HashMap<String, Employee>();
staff.put("E-1042", new Employee("Priya Nair", 72_000));
Employee e = staff.get("E-1042");
put(key, value)stores the pair. Keys are unique: putting a second value under the same key replaces the first, andputreturns the previous value, ornullif there was none.get(key)returns the value, ornullif the key is absent.getOrDefault(key, default)returns the default instead ofnullfor a missing key. This is great for counters (getOrDefault(word, 0)) and fallbacks.remove(key)deletes the entry and returns its value.size()counts the entries.containsKeyis fast.containsValuemust scan every entry, so it is O(n).putAll(otherMap)copies all entries from another map.
Iterating over a map
The simplest way to visit every entry is forEach with a lambda that receives both key and value:
scores.forEach((k, v) -> System.out.println("key=" + k + ", value=" + v));
You can also loop over entrySet(), keySet() or values(). These views are the subject of article 88.
Sorted-key extras of TreeMap
TreeMap implements SortedMap and NavigableMap, the map counterparts of the sorted set interfaces:
firstKey()andlastKey()return the smallest and largest key, andcomparator()returns the ordering, ornullfor natural order.floorKey,ceilingKey,lowerKeyandhigherKeyfind neighbouring keys.floorEntry,firstEntry,pollFirstEntryand the like return whole entries.headMap,tailMapandsubMapreturn range views, anddescendingMap()gives a reversed view.
A TreeMap<LocalDate, Rate> answering "which rate was in effect on this date?" with floorEntry(date) is a classic example.
Updating entries
The awkward part of working with maps is updating a value, such as incrementing a counter. The obvious code has a bug:
counts.put(word, counts.get(word) + 1); // NullPointerException the first time a word appears
The first time, get returns null, and unboxing null + 1 throws. There are several fixes, from clumsy to elegant:
counts.put(word, counts.getOrDefault(word, 0) + 1); // 1. default value
counts.putIfAbsent(word, 0); // 2. ensure the key exists...
counts.put(word, counts.get(word) + 1); // ...then update
counts.merge(word, 1, Integer::sum); // 3. best: one call, one lookup
merge(key, value, f) stores value if the key is absent. Otherwise it stores f(oldValue, value). For counting, that means "start at 1, or add 1". It also does the work in a single hash lookup.
Multimaps with computeIfAbsent
The other everyday pattern is a map whose values are collections, such as a book index from each term to the set of pages where it appears:
var index = new TreeMap<String, TreeSet<Integer>>();
index.computeIfAbsent(term, k -> new TreeSet<>()).add(page);
computeIfAbsent calls the function only if the key has no value, stores the result, and returns the current value, whether new or existing. That return value lets you chain .add(page). putIfAbsent(term, new TreeSet<>()) would build a throwaway set on every call, and it returns the previous value, which is null the first time, so you can't chain on it.
The full family

compute(k, f)always callsf(k, oldValueOrNull)and stores the result.computeIfPresent(k, f)callsf(k, old)only when a value exists. This is handy for decrementing.replaceAll(f)replaces every value withf(k, v).- For
merge,computeandcomputeIfPresent, a function that returnsnullremoves the entry. That gives you "decrement and delete when it reaches zero" in one call.
A complete example
import java.util.*;
public class Solution {
record Employee(String name, double salary) {}
public static void main(String[] args) {
// 1. basic operations
var staff = new HashMap<String, Employee>();
staff.put("E-1042", new Employee("Priya Nair", 72_000));
staff.put("E-2177", new Employee("Tom Okafor", 65_000));
staff.put("E-3305", new Employee("Lena Fischer", 81_000));
staff.put("E-4410", new Employee("Raj Mehta", 58_000));
System.out.println("size " + staff.size() + ", get(E-3305) " + staff.get("E-3305"));
System.out.println("get(E-9999) " + staff.get("E-9999"));
Employee old = staff.put("E-4410", new Employee("Raj Mehta", 63_000)); // replaces, returns the old value
System.out.println("put replaced " + old.salary() + " with " + staff.get("E-4410").salary());
System.out.println("remove(E-2177) " + staff.remove("E-2177").name() + ", containsKey " + staff.containsKey("E-2177"));
long numericId = 1042;
System.out.println("get(1042L) compiles but finds " + staff.get(numericId)); // get takes Object
// 2. a TreeMap visits keys in sorted order
var sorted = new TreeMap<>(staff);
sorted.forEach((id, e) -> System.out.println(" " + id + " -> " + e.name()));
System.out.println("firstKey " + sorted.firstKey() + ", lastKey " + sorted.lastKey()
+ ", floorKey(E-4000) " + sorted.floorKey("E-4000") + ", ceilingKey(E-4000) " + sorted.ceilingKey("E-4000"));
// 3. counting words: four ways
String text = "to be or not to be that is the question to ask";
String[] words = text.split(" ");
Map<String, Integer> counts = new TreeMap<>();
for (String w : words) counts.put(w, counts.getOrDefault(w, 0) + 1);
System.out.println("getOrDefault: " + counts);
counts.clear();
for (String w : words) { counts.putIfAbsent(w, 0); counts.put(w, counts.get(w) + 1); }
System.out.println("putIfAbsent: " + counts);
counts.clear();
for (String w : words) counts.merge(w, 1, Integer::sum);
System.out.println("merge: " + counts);
try {
Map<String, Integer> naive = new HashMap<>();
for (String w : words) naive.put(w, naive.get(w) + 1); // get returns null the first time
} catch (NullPointerException e) {
System.out.println("naive put(get + 1): NullPointerException");
}
// 4. multimap: a book index with computeIfAbsent
var index = new TreeMap<String, TreeSet<Integer>>();
String[][] entries = {{"lambda", "214"}, {"generics", "301"}, {"lambda", "198"}, {"stream", "350"}, {"generics", "287"}, {"lambda", "214"}};
for (String[] e : entries)
index.computeIfAbsent(e[0], k -> new TreeSet<>()).add(Integer.parseInt(e[1]));
System.out.println("index " + index);
// 5. compute, computeIfPresent, replaceAll, and null meaning "remove"
Map<String, Integer> stock = new TreeMap<>(Map.of("apples", 5, "pears", 2, "plums", 1));
stock.compute("apples", (k, v) -> v == null ? 1 : v + 10);
stock.compute("kiwis", (k, v) -> v == null ? 1 : v + 10);
stock.computeIfPresent("plums", (k, v) -> v - 1 == 0 ? null : v - 1); // null result removes the key
stock.computeIfPresent("mangos", (k, v) -> v + 1); // absent: nothing happens
stock.merge("pears", -2, (a, b) -> a + b == 0 ? null : a + b); // merge to null removes too
System.out.println("stock " + stock);
stock.replaceAll((k, v) -> v * 2);
System.out.println("doubled " + stock);
// 6. null values: methods disagree
Map<String, Integer> m = new HashMap<>();
m.put("C++", null);
System.out.println("containsKey(C++) " + m.containsKey("C++") + ", getOrDefault(C++, -1) " + m.getOrDefault("C++", -1));
m.putIfAbsent("C++", 1);
System.out.println("after putIfAbsent: " + m);
// 7. pre-sized map (Java 19+)
Map<Integer, String> big = HashMap.newHashMap(500);
for (int i = 0; i < 500; i++) big.put(i, "v" + i);
System.out.println("newHashMap(500) holds " + big.size() + ", containsValue(v499) " + big.containsValue("v499"));
}
}
size 4, get(E-3305) Employee[name=Lena Fischer, salary=81000.0]
get(E-9999) null
put replaced 58000.0 with 63000.0
remove(E-2177) Tom Okafor, containsKey false
get(1042L) compiles but finds null
E-1042 -> Priya Nair
E-3305 -> Lena Fischer
E-4410 -> Raj Mehta
firstKey E-1042, lastKey E-4410, floorKey(E-4000) E-3305, ceilingKey(E-4000) E-4410
getOrDefault: {ask=1, be=2, is=1, not=1, or=1, question=1, that=1, the=1, to=3}
putIfAbsent: {ask=1, be=2, is=1, not=1, or=1, question=1, that=1, the=1, to=3}
merge: {ask=1, be=2, is=1, not=1, or=1, question=1, that=1, the=1, to=3}
naive put(get + 1): NullPointerException
index {generics=[287, 301], lambda=[198, 214], stream=[350]}
stock {apples=15, kiwis=1}
doubled {apples=30, kiwis=2}
containsKey(C++) true, getOrDefault(C++, -1) null
after putIfAbsent: {C++=1}
newHashMap(500) holds 500, containsValue(v499) true
All three word-counting approaches give the same result, and merge is the shortest. In the inventory, plums and pears disappear because their functions returned null, while kiwis appears because compute runs even for an absent key.
Common questions
What is the easiest way to count occurrences with a map?
counts.merge(word, 1, Integer::sum). It stores 1 for a new key and adds 1 to an existing count, in one lookup. With streams, Collectors.groupingBy(w -> w, Collectors.counting()) does the same.
Why does map.get(key) return null even though I put the key in?
Usually the key you pass isn't equal to the stored key: a different type (an Integer for Long keys), a key object mutated after insertion, or a class without matching equals and hashCode. get takes an Object, so the compiler won't warn about a wrong key type.
HashMap or TreeMap?
HashMap for plain lookup by key, which covers most cases. TreeMap when you need keys in sorted order or range queries such as floorKey, headMap and subMap. For insertion order with hash speed, use LinkedHashMap.
Can HashMap store null keys and values?
Yes, one null key and any number of null values. TreeMap with natural ordering rejects null keys, and Map.of, Map.copyOf and ConcurrentHashMap reject null keys and values. Avoid storing null values, because get can't distinguish them from missing keys and the update methods treat them as absent.
Is HashMap thread-safe?
No. Concurrent updates can lose entries or corrupt the map. Use ConcurrentHashMap when several threads share a map. Its merge and compute methods are atomic.
API reference
java.util.Map<K, V>
| Method | Description |
|---|---|
V get(Object key) | value for the key, or null if absent (some maps forbid null keys) |
default V getOrDefault(Object key, V defaultValue) | value for the key, or defaultValue if absent |
V put(K key, V value) | associates the value with the key; returns the old value or null |
void putAll(Map<? extends K, ? extends V> entries) | adds all entries from another map |
V remove(Object key) | removes the key's entry and returns its value |
boolean containsKey(Object key), boolean containsValue(Object value) | membership tests (containsValue is O(n) for hash and tree maps) |
default void forEach(BiConsumer<? super K, ? super V> action) | applies the action to every key/value pair |
default V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> f) | stores value if the key is absent or null, else f(old, value); a null result removes the key; returns the new value |
default V compute(K key, BiFunction<? super K, ? super V, ? extends V> f) | stores f(key, get(key)); a null result removes the key |
default V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> f) | if the key has a non-null value, stores f(key, value); a null result removes the key |
default V computeIfAbsent(K key, Function<? super K, ? extends V> f) | if the key is absent or null, stores f(key) unless it is null; returns the current value |
default void replaceAll(BiFunction<? super K, ? super V, ? extends V> f) | replaces every value with f(key, value) |
default V putIfAbsent(K key, V value) | if the key is absent or null, stores the value and returns null; otherwise returns the existing value |
java.util.HashMap<K, V>
| Method | Description |
|---|---|
HashMap(), HashMap(int initialCapacity), HashMap(int initialCapacity, float loadFactor) | empty hash map; default load factor 0.75 |
static <K, V> HashMap<K, V> newHashMap(int numMappings) (Java 19) | empty map sized to hold numMappings entries without rehashing |
java.util.TreeMap<K, V>
| Method | Description |
|---|---|
TreeMap(), TreeMap(Comparator<? super K> c) | empty tree map with natural or comparator ordering of keys |
TreeMap(Map<? extends K, ? extends V> entries) | tree map holding the entries, in natural key order |
TreeMap(SortedMap<K, ? extends V> entries) | tree map holding the entries, with the same comparator |
java.util.SortedMap<K, V>
| Method | Description |
|---|---|
Comparator<? super K> comparator() | the key comparator, or null for natural ordering |
K firstKey(), K lastKey() | smallest or largest key |
Summary
- A map associates unique keys with values.
HashMapis O(1) on average and unordered.TreeMapis O(log n) and sorted by key. putreplaces and returns the old value,getreturnsnullfor missing keys, andgetOrDefaultsupplies a fallback.getandcontainsKeyaccept anyObject, so a wrong key type compiles and silently finds nothing.- Use
merge(k, 1, Integer::sum)for counting andcomputeIfAbsent(k, k -> new ArrayList<>())for multimaps. - A function result of
nullremoves the entry. Avoid storingnullvalues at all, because the methods treat them inconsistently.
Practice Questions
What does put return, and how can you use that?
The previous value for the key, or null if there was none. You can detect replacements, for example if (map.put(k, v) != null) log("duplicate key " + k). With null values in the map, though, you can't tell "absent" from "was null".
Rewrite this using one Map method: if (!m.containsKey(k)) m.put(k, new ArrayList<>()); m.get(k).add(x);
m.computeIfAbsent(k, key -> new ArrayList<>()).add(x); It does one lookup instead of up to three, and it creates the list only when needed.
A Map<Long, String> named users has an entry for 42L. What does users.get(42) return, and why?
null. The literal 42 is boxed to an Integer, and Integer.valueOf(42).equals(Long.valueOf(42)) is false. Because get takes Object, the compiler doesn't complain.
How do you decrement a counter and delete the key when it reaches zero, in one call?
counts.computeIfPresent(k, (key, v) -> v == 1 ? null : v - 1);, or counts.merge(k, -1, (a, b) -> a + b == 0 ? null : a + b);. A null result removes the entry.
When would you pick a TreeMap over a HashMap?
When you need keys in sorted order (sorted reports or output), or range and neighbour queries such as floorKey, headMap or subMap. Typical uses are time-series lookups, leaderboards and interval schedules.
Previous: Java Queues and Deques: ArrayDeque, LinkedList and PriorityQueue
Next: Java Map Views and Special Maps: LinkedHashMap, EnumMap, WeakHashMap and IdentityHashMap
Related reading
- Java Queues and Deques: ArrayDeque, LinkedList and PriorityQueue
- Java HashSet and TreeSet: Hash Tables, Hash Codes and Sorted Sets
- Java LinkedList vs ArrayList: Linked Lists, ListIterator and Array Lists
- Java Collection Interfaces: List, Set, Queue, Map and Sequenced Collections
- The Java Collections Framework: Interfaces, Implementations and Iterators

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.