Java Map.entrySet, Map.keySet and Map.values
Use entrySet to visit keys and values together, keySet for just the keys, and values for the mapped values.
A simple example
Map.entrySet, Map.keySet and Map.values
- Start with B = 2, A = 1
- Do this Visit entries in key order
- Result A = 1, then B = 2
Syntax
for (var entry : sales.entrySet())
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaPrint shelf totals in aisle order
A stockroom supervisor sends a short inventory message each evening. Both the aisle name and its count belong on each line, and the message must follow aisle order every time.
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;
class Main {
public static void main(String[] args) throws Exception {
var stock = new TreeMap<>(Map.of("B", 2, "A", 4));
var lines = new ArrayList<String>();
for (var entry : stock.entrySet()) {
lines.add(entry.getKey() + "=" + entry.getValue());
}
System.out.println(String.join(", ", lines));
}
}
A=4, B=2
TreeMap visits the aisle keys in sorted order. Each entry supplies its own count.
Count outlets and sum their deliveries
Two outlets report the number of crates they received today. The coordinator counts the distinct outlet keys and adds all crate counts, including equal counts from different outlets.
import java.util.Map;
class Main {
public static void main(String[] args) throws Exception {
var deliveries = Map.of("East", 3, "West", 3);
int total = 0;
for (int crates : deliveries.values()) total += crates;
System.out.println(deliveries.keySet().size() + " outlets, " + total + " crates");
}
}
2 outlets, 6 crates
There are two keys and two values of three. The values view retains both counts.
Print stock by aisle
A delivery entered the second aisle before the first. The clerk sorts the keys before printing each key beside its associated value. What appears on the labels?
What to watch for
Map views are backed by the map. HashMap has no guaranteed iteration order, so sort or use a suitable ordered map when order matters.