Java HashMap
A map stores key–value pairs: a word and its definition, a username and their score, a product code and its price. You look up a value by its key instead of by an index. HashMap from java.util is the most widely used map implementation. Keys are unique; each key maps to exactly one value.
Creating and using a map
import java.util.HashMap;
import java.util.Map;
class Main {
public static void main(String[] args) {
Map<String, Integer> stock = new HashMap<>();
stock.put("apples", 40);
stock.put("bananas", 25);
stock.put("cherries", 120);
System.out.println(stock.get("bananas"));
System.out.println(stock.get("kiwis")); // missing key
System.out.println(stock.containsKey("apples"));
System.out.println("Size: " + stock.size());
stock.put("apples", 35); // same key: value replaced
stock.remove("cherries");
System.out.println(stock.get("apples") + ", size " + stock.size());
}
}25
null
true
Size: 3
35, size 2
The first type parameter is the key type, the second the value type. get returns null for keys that aren't in the map.
Common methods
| Method | Description |
|---|---|
put(k, v) |
add or replace the value for k |
get(k) |
value for k, or null |
getOrDefault(k, d) |
value for k, or d if missing |
containsKey(k) / containsValue(v) |
membership tests |
remove(k) |
delete the entry |
putIfAbsent(k, v) |
only add if k isn't present |
merge(k, v, fn) |
combine a new value with an existing one |
keySet() / values() / entrySet() |
views for looping |
About iteration order
A HashMap organises its entries by the keys' hash codes, so its iteration order is not defined — it isn't insertion order or alphabetical order, and it can change as the map grows. When the order of output matters, pick a different implementation:
| Implementation | Iteration order |
|---|---|
HashMap |
unspecified (fastest) |
LinkedHashMap |
insertion order |
TreeMap |
sorted by key |
The examples below use TreeMap and LinkedHashMap so that the printed order is predictable; the methods are the same for all three.
Looping through a map
import java.util.Map;
import java.util.TreeMap;
class Main {
public static void main(String[] args) {
Map<String, Double> prices = new TreeMap<>();
prices.put("tea", 2.80);
prices.put("coffee", 3.20);
prices.put("juice", 4.10);
for (String item : prices.keySet()) {
System.out.println("Item: " + item);
}
for (Map.Entry<String, Double> e : prices.entrySet()) {
System.out.printf("%-7s %.2f%n", e.getKey(), e.getValue());
}
double total = 0;
for (double p : prices.values()) total += p;
System.out.printf("Sum of prices: %.2f%n", total);
prices.forEach((item, price) -> System.out.println(item + " -> " + price));
}
}Item: coffee
Item: juice
Item: tea
coffee 3.20
juice 4.10
tea 2.80
Sum of prices: 10.10
coffee -> 3.2
juice -> 4.1
tea -> 2.8
Counting with a map
Counting occurrences is one of the most frequent uses of a map. merge and getOrDefault keep it short:
import java.util.LinkedHashMap;
import java.util.Map;
class Main {
public static void main(String[] args) {
String text = "the cat and the dog and the bird";
Map<String, Integer> counts = new LinkedHashMap<>();
for (String word : text.split(" ")) {
counts.merge(word, 1, Integer::sum); // add 1, or start at 1
}
System.out.println(counts);
Map<Character, Integer> letters = new LinkedHashMap<>();
for (char c : "banana".toCharArray()) {
letters.put(c, letters.getOrDefault(c, 0) + 1);
}
System.out.println(letters);
}
}{the=3, cat=1, and=2, dog=1, bird=1}
{b=1, a=3, n=2}
Grouping values
A map's values can be collections. computeIfAbsent creates the list the first time a key is seen:
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
class Main {
public static void main(String[] args) {
String[] names = {"Anna", "Ben", "Alex", "Bella", "Chris", "Amir"};
Map<Character, List<String>> byLetter = new TreeMap<>();
for (String n : names) {
byLetter.computeIfAbsent(n.charAt(0), k -> new ArrayList<>()).add(n);
}
System.out.println(byLetter);
System.out.println("Names with A: " + byLetter.get('A').size());
}
}{A=[Anna, Alex, Amir], B=[Ben, Bella], C=[Chris]}
Names with A: 3
Note: Objects used as keys must implement
equalsandhashCodeconsistently.String, the wrapper classes, enums and records already do. If you change a key object's fields after inserting it, the map may no longer find it — prefer immutable keys.
Test yourself
What happens when you put a key that already exists in a HashMap?
- An exception is thrown
- A duplicate entry is added
- The old value is replaced
- The put is ignored
Which map keeps its keys sorted?
- HashMap
- LinkedHashMap
- TreeMap
- All of them
What does map.getOrDefault("x", 0) return if "x" is not a key?
- null
- 0
- "x"
- It throws