Java 25 (LTS) reference · Map and HashMap Methods
Java Map entrySet() Method
Return the map's entries (key-value pairs) for looping over keys and values together.
Java 25 (LTS) Since Java 1.0
Syntax
map.entrySet()
Return value
A Set<Map.Entry<K, V>> view.
Examples
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Integer> stock = new TreeMap<>(Map.of("mug", 12, "tea", 3, "kettle", 0));
for (Map.Entry<String, Integer> e : stock.entrySet()) {
System.out.println(e.getKey() + ": " + e.getValue());
}
}
}
Output
kettle: 0 mug: 12 tea: 3
Run this on your computer — see “Get Started” for setup.
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Integer> stock = new TreeMap<>(Map.of("mug", 12, "tea", 3));
stock.forEach((item, qty) -> System.out.println(item + " x" + qty));
System.out.println(stock.keySet() + " " + stock.values());
}
}
Output
mug x12 tea x3 [mug, tea] [12, 3]
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| Java Java 1.0 | Added |
Related
map.get()· Return the value for a key, or null if the key isn't present. Use getOrDefault() to avoid nulls.stream.filter()· Keep only the elements that match a condition. Intermediate and lazy: nothing runs until a terminal operation.- Java HashMap · tutorial