Java HashMap
A list finds items by their position. Often you want to find them by something more meaningful: a phone number by a name, a price by a product, a capital city by a country. A map stores pairs of a key and a value, and finds a value by its key very quickly. The most used map in Java is HashMap.
put and get
You give two types in angle brackets: the key type and the value type.
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, String> capitals = new HashMap<>();
capitals.put("India", "New Delhi");
capitals.put("Japan", "Tokyo");
capitals.put("Kenya", "Nairobi");
System.out.println(capitals.get("Japan"));
System.out.println(capitals.get("Peru"));
System.out.println(capitals.size());
capitals.put("Japan", "TOKYO");
System.out.println(capitals.get("Japan"));
}
}Tokyo null 3 TOKYO
put(key, value)adds a pair. If the key is already there, its value is replaced: each key appears only once.get(key)returns the value, ornullwhen the key is not in the map.
Checking, defaults and removing
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, Integer> stock = new HashMap<>();
stock.put("pen", 40);
stock.put("eraser", 12);
System.out.println(stock.containsKey("pen"));
System.out.println(stock.getOrDefault("ruler", 0));
stock.remove("eraser");
System.out.println(stock.containsKey("eraser"));
stock.put("pen", stock.get("pen") - 5);
System.out.println(stock);
}
}true
0
false
{pen=35}getOrDefault avoids the null (and the NullPointerException that unboxing it would cause) by giving a default value for missing keys.
Looping over a map
keySet() gives all the keys, values() all the values, and entrySet() all the pairs. A HashMap does not keep the pairs in the order you added them; the order depends on the keys' hash codes:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Integer> scores = new HashMap<>();
scores.put("Ravi", 82);
scores.put("Anu", 95);
scores.put("Zoya", 77);
for (Map.Entry<String, Integer> e : scores.entrySet()) {
System.out.println(e.getKey() + " -> " + e.getValue());
}
int total = 0;
for (int s : scores.values()) {
total += s;
}
System.out.println("Total: " + total);
}
}Ravi -> 82 Zoya -> 77 Anu -> 95 Total: 254
Counting with a map
Counting how often something appears is the classic use of a map. merge adds 1 to the count, or puts 1 when the key is new. A TreeMap keeps its keys sorted, which is handy for printing:
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
String text = "the cat and the dog and the bird";
Map<String, Integer> counts = new TreeMap<>();
for (String word : text.split(" ")) {
counts.merge(word, 1, Integer::sum);
}
System.out.println(counts);
System.out.println("'the' appears " + counts.get("the") + " times");
}
}{and=2, bird=1, cat=1, dog=1, the=3}
'the' appears 3 timesInteger::sum is a method reference, a short form of a lambda that you will meet in Lambda. Keys must have proper equals and hashCode methods; strings, wrapper classes and records do.
Practice exercises
- Store the prices of five fruits in a map and print the price of one the user types.
- Count how many times each letter appears in the word "programming".
- Print the contents of a map sorted by key using a
TreeMap.