entrySet()
Iterate keys and values together without extra lookups, update values in place, and sort or filter a map through its entries.
Set<Map.Entry<K, V>> entrySet()- Added in Java Java 1.2
Return value
Set<Map.Entry<K, V>>A set view of the map's mappings. It is backed by the map: removals through the view change the map, and changes to the map show up in the view.
Errors
None directly. Adding to the view throws UnsupportedOperationException; Entry.setValue throws UnsupportedOperationException on unmodifiable maps; iterating while the map is structurally modified throws ConcurrentModificationException on HashMap, LinkedHashMap and TreeMap.
entrySet() returns the map's mappings as a Set<Map.Entry<K, V>>. Each entry has getKey() and getValue(). When you need both the key and the value, loop over the entries; looping over keySet() and calling get for each key does a second lookup per entry for no gain.
for (Map.Entry<String, String> e : headers.entrySet()) {
out.println(e.getKey() + ": " + e.getValue());
}
var e works too and saves typing the generic type.
It is a view, not a copy
The set is backed by the map. Removing through it removes from the map: entrySet().removeIf(...) is the clean way to drop entries that match a condition. You cannot add to it; add throws UnsupportedOperationException. Changing the map's structure while you loop over the view throws ConcurrentModificationException.
Updating values in place
For HashMap, LinkedHashMap and TreeMap, entry.setValue(v) during iteration writes straight back to the map. Entries of unmodifiable maps, entries from Map.entry(k, v) and entries returned by TreeMap.firstEntry() are immutable and throw. To transform every value, replaceAll((k, v) -> ...) is shorter.
Do not keep entry objects after the loop. Their behaviour after the map changes is undefined; copy the key and value out, or use Map.Entry.copyOf(e) (Java 17) for an independent, unmodifiable entry.
Sorting and filtering
A map has no "sort by value" method, but its entries can be streamed. Map.Entry.comparingByValue() and comparingByKey() are ready-made comparators. Collect the result into a LinkedHashMap to keep the sorted order, or into a TreeMap to sort by key.
Order
Entries come out in the map's own order: undefined for HashMap and Map.of, insertion order for LinkedHashMap, key order for TreeMap. When the output is a query string, a log line or a JSON body that tests compare, choose a map with a defined order.
Example
When to use it
- Building a URL-encoded query string or form body from a map of parameters.
- Writing every response header from a map onto an outgoing HTTP response.
- Reporting the busiest endpoints by sorting a hit-count map by value.
Frequently asked questions
How do I iterate over a HashMap in Java?
Use for (Map.Entry<K, V> e : map.entrySet()) and read e.getKey() and e.getValue(), or call map.forEach((k, v) -> ...). Both visit each entry once.
Is entrySet faster than keySet?
When you need the values too, yes: keySet plus get does an extra lookup for every key, while entrySet hands you the key and value together.
How do I sort a map by value?
Stream the entries, sort them with Map.Entry.comparingByValue(), and collect into a LinkedHashMap with Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, LinkedHashMap::new) to keep that order.
More examples
Top endpoints by hit count
Sorting the entry stream gives a stable order even though Map.of itself has none. The explicit type witness is needed because reversed() stops Java inferring the comparator's types.
void main() {
Map<String, Integer> hits = Map.of(
"/login", 120,
"/products", 480,
"/cart", 95,
"/health", 3000);
hits.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.limit(3)
.forEach(e -> IO.println(e.getKey() + " " + e.getValue()));
}
// Output:
// /health 3000
// /products 480
// /login 120Updating values in place with setValue
setValue on a TreeMap entry writes through to the map during the loop. Entries created with Map.entry are standalone and unmodifiable.
void main() {
Map<String, Integer> pricesInPence = new TreeMap<>(Map.of("basic", 1000, "pro", 2500));
for (Map.Entry<String, Integer> e : pricesInPence.entrySet()) {
e.setValue(e.getValue() + 200);
}
IO.println(pricesInPence);
try {
Map.entry("basic", 1000).setValue(0);
} catch (UnsupportedOperationException ex) {
IO.println("Map.entry is immutable");
}
}
// Output:
// {basic=1200, pro=2700}
// Map.entry is immutableFiltering a map into a new map
Streaming the entries keeps key and value together through the filter. The four-argument toMap picks the map type, here a TreeMap so the output is sorted.
void main() {
Map<String, String> env = new TreeMap<>(Map.of(
"APP_PORT", "8080",
"APP_MODE", "prod",
"PATH", "/usr/bin",
"HOME", "/home/app"));
Map<String, String> appConfig = env.entrySet().stream()
.filter(e -> e.getKey().startsWith("APP_"))
.collect(Collectors.toMap(
e -> e.getKey().substring(4).toLowerCase(Locale.ROOT),
Map.Entry::getValue,
(a, b) -> a,
TreeMap::new));
IO.println(appConfig);
}
// Output:
// {mode=prod, port=8080}
Discussion