Sub topic 12
Key-Value Lookup with Map and HashMap
Sometimes you don't want to find data by position. You want to find it by name. A phone book works this way. You look up "Ana" and get her number. You don't care that she is the 14th entry.
Java gives you the Map interface for this job. This chapter shows what a map is, how HashMap stores data, and which methods you will use every day.
What a Map Is
A map is a collection that stores key-value pairs. A key is the thing you look up by, like a name. A value is the data linked to that key, like a phone number. Together, one key and its value are called an entry.
Maps follow a few rules:
- Each key appears at most once. Keys are unique, like the elements of a
Set. - Values can repeat. Two people can share a phone number.
- Each key points to exactly one value.
Map is an interface. It describes what a map can do. HashMap is a class that implements it. HashMap is the most common choice.
A map uses two type parameters, one for the key type and one for the value type. Map<String, Integer> means "keys are strings, values are integers."
Your First HashMap
Here is a small phone book. Read the comments to see what each line prints.
import java.util.HashMap;
import java.util.Map;
public class PhoneBook {
public static void main(String[] args) {
Map<String, String> phones = new HashMap<>();
phones.put("Ana", "555-0101");
phones.put("Ben", "555-0102");
System.out.println(phones.get("Ana")); // 555-0101
System.out.println(phones.get("Zoe")); // null
String old = phones.put("Ana", "555-0199");
System.out.println(old); // 555-0101
System.out.println(phones.get("Ana")); // 555-0199
System.out.println(phones.size()); // 2
phones.remove("Ben");
System.out.println(phones.containsKey("Ben")); // false
System.out.println(phones.isEmpty()); // false
}
}The example shows four things:
put(key, value)adds an entry.get(key)returns the value, ornullif the key is missing.nullis Java's word for "no object here."- Calling
putwith a key that already exists replaces the old value. It does not add a second entry.putreturns the old value, ornullif there was none. remove(key)deletes the entry and returns its value.
The Core Methods
| Method | What it does | Returns |
|---|---|---|
| `put(k, v)` | Adds or replaces the value for `k` | Old value, or `null` |
| `get(k)` | Looks up the value for `k` | Value, or `null` |
| `getOrDefault(k, d)` | Looks up `k`, uses `d` if missing | Value, or `d` |
| `containsKey(k)` | Checks if `k` is a key | `true` or `false` |
| `containsValue(v)` | Checks if `v` is any value (slow) | `true` or `false` |
| `remove(k)` | Deletes the entry for `k` | Old value, or `null` |
| `putIfAbsent(k, v)` | Adds only if `k` is missing | Existing value, or `null` |
| `merge(k, v, f)` | Adds `v`, or combines it with the old value using `f` | New value |
| `size()` | Counts the entries | An `int` |
containsKey is fast. containsValue is slow because it must check every entry. The next section explains why.
How HashMap Finds a Key
A HashMap does not search from the start, the way you would scan an array. It uses each key's hash code. A hash code is an int that the key's hashCode() method calculates.
The map keeps an internal array of slots called buckets. To store or find a key, it does this:
- Calls
key.hashCode()to get a number. - Turns that number into a bucket position.
- Looks only in that bucket.
- Uses
equals()to compare the key with each key already in that bucket.
Each bucket usually holds only one or two entries, so get, put, and containsKey take about the same time whether the map has 10 entries or 10 million. People call this constant time. Values are not hashed, so containsValue has to check every entry.
Counting Things with merge and getOrDefault
Counting is one of the most common uses for a map. Each word is a key, and its count is the value.
import java.util.HashMap;
import java.util.Map;
public class WordCount {
public static void main(String[] args) {
String[] words = {"to", "be", "or", "not", "to", "be"};
Map<String, Integer> counts = new HashMap<>();
for (String w : words) {
counts.merge(w, 1, Integer::sum);
}
System.out.println(counts.get("to")); // 2
System.out.println(counts.get("not")); // 1
System.out.println(counts.getOrDefault("maybe", 0)); // 0
System.out.println(counts.containsKey("or")); // true
}
}merge(w, 1, Integer::sum) means: "If w is new, store 1. If it exists, add 1 to the old value." Integer::sum is a short way to name a method that adds two numbers.
You can write the same loop with getOrDefault. It is longer, but some beginners find it easier to read:
for (String w : words) {
counts.put(w, counts.getOrDefault(w, 0) + 1);
}Null and Missing Keys
HashMap allows one null key and any number of null values. That leads to a small trap. If get returns null, it could mean the key is missing, or it could mean the key is present with a null value. containsKey tells the two cases apart.
The simplest fix is to avoid storing null values at all. Then null from get always means "missing."
Keys Need equals and hashCode
The lookup steps above depend on hashCode() and equals(). If your key class does not override them, Java compares keys by identity. Two separate objects with the same fields then count as different keys.
import java.util.HashMap;
import java.util.Map;
public class BrokenKeyDemo {
static class Seat {
final int row;
final int number;
Seat(int row, int number) {
this.row = row;
this.number = number;
}
}
public static void main(String[] args) {
Map<Seat, String> bookings = new HashMap<>();
bookings.put(new Seat(3, 7), "Ana");
System.out.println(bookings.get(new Seat(3, 7))); // null
}
}The second new Seat(3, 7) is a different object, so it gets a different hash code, and the map never finds Ana's booking. You can fix this by overriding equals and hashCode, as shown in the chapter on equality. On Java 16 or later you can also use a record, a short class form that writes both methods for you:
import java.util.HashMap;
import java.util.Map;
public class FixedKeyDemo {
record Seat(int row, int number) {}
public static void main(String[] args) {
Map<Seat, String> bookings = new HashMap<>();
bookings.put(new Seat(3, 7), "Ana");
System.out.println(bookings.get(new Seat(3, 7))); // Ana
}
}HashMap Has No Order
HashMap makes no promise about order. If you print a map, the entries may come out in any order, and the order can change as the map grows. Never write code that depends on it. When you need insertion order or sorted keys, use LinkedHashMap or TreeMap, which a later chapter covers. The next chapter shows how to loop over every entry.
Common Mistakes
- Expecting
putto keep both values. A secondputwith the same key replaces the first value. To keep several values per key, use aMap<String, List<String>>. - Unboxing a missing value.
int x = map.get(k)crashes whenkis missing. - Using a raw
Map. Always give type parameters, such asMap<String, Integer>, so the compiler catches type mistakes. - Custom keys without
equalsandhashCode. Lookups quietly returnnull.
Exercise
What does this code print, and why? Map<String, Integer> m = new HashMap<>(); m.put("a", 1); Integer r = m.put("a", 5); System.out.println(r + " " + m.get("a") + " " + m.size());
Show answer
It prints "1 5 1". The second put replaces the value for "a" and returns the old value, 1. The map still has only one key, so size is 1.
Exercise
Write a loop that counts how many times each character appears in the string "banana", using a Map<Character, Integer>. What is the count for 'a'?
Show answer
Use Map<Character, Integer> counts = new HashMap<>(); for (char c : "banana".toCharArray()) { counts.merge(c, 1, Integer::sum); }. The count for 'a' is 3, for 'n' it is 2, and for 'b' it is 1.
Exercise
A map holds Map<String, Integer> stock and the code runs int pears = stock.get("pears"); when "pears" is not a key. What happens, and how do you fix it?
Show answer
get returns null, and unboxing null into an int throws a NullPointerException. Fix it with int pears = stock.getOrDefault("pears", 0); or check stock.containsKey("pears") first.