Map
A Map is not a Collection: it holds pairs of a key and a value, and it answers one question quickly, what is the value for this key. The keys are unique, a key that is put twice replaces the value, and a key that is not there answers null, which is the first thing to handle in every program that reads a map.
A map and its methods
The program puts three ages, reads one, asks for a key it never put, checks what is there, removes one entry and prints the three views:
import java.util.HashMap;
import java.util.Map;
public class Basics {
public static void main(String[] args) {
Map<String, Integer> ages = new HashMap<>();
ages.put("Ada", 36);
ages.put("Grace", 45);
ages.put("Edsger", 72);
System.out.println(ages.size());
System.out.println(ages.get("Ada"));
System.out.println(ages.get("Alan"));
System.out.println(ages.getOrDefault("Alan", 0));
System.out.println(ages.containsKey("Grace") + " " + ages.containsValue(72));
ages.remove("Edsger");
System.out.println(ages.keySet());
System.out.println(ages.values());
System.out.println(ages);
}
}
javac -Xlint:all Basics.java
java Basics
3
36
null
0
true true
[Grace, Ada]
[45, 36]
{Grace=45, Ada=36}
The third and fourth lines are the difference between get and getOrDefault: the first answers null for a key that is not there, the second answers the default the caller passes. The last three lines are views of the same map, and their order is the order of the hash table, which is no order at all.
A key that is not there
A HashMap may hold a null value, so get returning null does not prove that the key is absent; containsKey does. The three shapes a program uses are a default with getOrDefault, a check with containsKey before an update, and merge or compute when the update is an expression.
A null key is allowed in a HashMap and is a bad idea wherever the key is a name or an id: every read then has to decide whether a missing name and a null name are the same thing. Map.of and TreeMap refuse a null key outright.
keySet, values and entrySet
The three views are live: a change to the map is visible through them, and a removal through a view removes from the map. The iteration that reads both the key and the value uses entrySet, because Map.Entry carries the two together:
import java.util.Map;
public class Entries {
public static void main(String[] args) {
Map<String, Integer> stock = Map.of("apples", 3, "pears", 0, "figs", 7);
int total = 0;
for (Map.Entry<String, Integer> entry : stock.entrySet()) {
total += entry.getValue();
System.out.printf("%-8s %2d%n", entry.getKey(), entry.getValue());
}
System.out.println("total " + total);
Map<String, Integer> copy = new java.util.TreeMap<>(stock);
copy.put("apples", 4);
System.out.println(copy);
}
}
javac -Xlint:all Entries.java
java Entries
figs 7
pears 0
apples 3
total 10
{apples=4, figs=7, pears=0}
The first block is in the order Map.of happens to iterate, which is not guaranteed; the last line is sorted because the copy is a TreeMap. The zero for pears is not a missing entry: the key is there with the value zero, and a program that sums the values must not treat it as absent.
merge and computeIfAbsent
Counting words is the smallest map program there is, and merge writes it in one line: put 1 with the key, or add one to what is there. The second map builds a string per key with computeIfAbsent, and the third changes one value with computeIfPresent:
import java.util.LinkedHashMap;
import java.util.Map;
public class Updating {
public static void main(String[] args) {
Map<String, Integer> counts = new LinkedHashMap<>();
for (String word : new String[] {"b", "a", "b", "c", "b", "a"}) {
counts.merge(word, 1, Integer::sum);
}
System.out.println(counts);
Map<String, StringBuilder> index = new LinkedHashMap<>();
String[][] rows = {{"a", "1"}, {"b", "2"}, {"a", "3"}};
for (String[] row : rows) {
index.computeIfAbsent(row[0], k -> new StringBuilder()).append(row[1]);
}
System.out.println(index);
counts.computeIfPresent("c", (k, v) -> v + 10);
System.out.println(counts);
}
}
javac -Xlint:all Updating.java
java Updating
{b=3, a=2, c=1}
{a=13, b=2}
{b=3, a=2, c=11}
merge takes the key, the value to put when the key is new, and a function that combines the old value with the new one; the function is a lambda and Integer::sum is a method reference, both from lesson 082 and lesson 084. computeIfAbsent creates the value once per key and returns it, so the append writes into the map. The last line changes the value of a key that exists and leaves the others alone, which is the difference from computeIfAbsent.
Three maps, three orders
The order of the three implementations is the order of the three sets of lesson 071, for the same reason: a hash table has none, a linked one keeps the insertion order, and a tree one keeps the keys sorted:
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
public class Orders {
public static void main(String[] args) {
Map<String, Integer> hash = new HashMap<>();
Map<String, Integer> linked = new LinkedHashMap<>();
Map<String, Integer> tree = new TreeMap<>();
for (String key : new String[] {"pear", "apple", "fig"}) {
hash.put(key, key.length());
linked.put(key, key.length());
tree.put(key, key.length());
}
System.out.println("hash " + hash);
System.out.println("linked " + linked);
System.out.println("tree " + tree);
System.out.println("first key " + tree.keySet().iterator().next());
}
}
javac -Xlint:all Orders.java
java Orders
hash {apple=5, pear=4, fig=3}
linked {pear=4, apple=5, fig=3}
tree {apple=5, fig=3, pear=4}
first key apple
A TreeMap also answers questions a hash map cannot cheaply: firstKey, headMap and floorKey are the range queries of a sorted map. The cost is logarithmic access instead of constant, which is the trade a sorted structure always makes.
Exercises
- Add a fourth word to Updating and print the counts again.
- Read a key that is not there with get and with containsKey and print both.
- Copy the counts into a TreeMap and print the keys in order.
- Build a map of word to its length with computeIfAbsent and append a comma and the next length.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
getanswer for a key the map does not have?Answer
null
A missing key has no value, so the answer is null and the caller must handle it.
-
Which view gives the key and the value together?
Answer
entrySet
Map.Entry carries both, so one iteration reads the pair.
-
What does
merge(key, 1, Integer::sum)do?Answer
Puts 1 for a new key and adds one to the value of an existing one
The value is the default and the function combines it with the old value.
-
What does this program print?
import java.util.HashMap; import java.util.Map; public class Q1 { public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); map.put("a", 1); map.put("a", 2); System.out.println(map.size()); System.out.println(map.get("a")); } }Answer
1 then 2
A key is unique, so the second put replaces the value and the size stays one.
-
What does this program print?
import java.util.HashMap; import java.util.Map; public class Q2 { public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); System.out.println(map.getOrDefault("x", 7)); System.out.println(map.get("x") == null); } }Answer
7 then true
The default is returned without storing anything, and the map stays empty.
-
What does this program print?
import java.util.LinkedHashMap; import java.util.Map; public class Q3 { public static void main(String[] args) { Map<String, Integer> map = new LinkedHashMap<>(); map.put("b", 2); map.put("a", 1); map.put("b", 3); System.out.println(map); } }Answer
{b=3, a=1}
The linked map keeps the order of first insertion, and the second put only changes the value.
-
What does this program print?
import java.util.Map; import java.util.TreeMap; public class Q4 { public static void main(String[] args) { Map<String, Integer> map = new TreeMap<>(); map.put("c", 3); map.put("a", 1); map.put("b", 2); System.out.println(map.keySet()); } }Answer
[a, b, c]
The sorted map iterates its keys in their natural order.
-
What does this program print?
import java.util.HashMap; import java.util.Map; public class Q5 { public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); map.put("a", 1); map.merge("a", 5, Integer::sum); map.merge("b", 5, Integer::sum); System.out.println(map.get("a") + " " + map.get("b")); } }Answer
6 5
The existing key is combined to six, and the new key takes the value five.
-
Which map gives range queries such as the first key?
Answer
TreeMap
Only the sorted map knows the order of its keys, so it can answer firstKey and headMap.
-
What is the difference between a missing key and a key with a null value?
Answer
containsKey tells them apart, because get answers null for both
HashMap allows a null value, so only containsKey proves that the key is present.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev