Map & Set in Java

From the Java cheat sheet · Arrays & Collections · verified Jul 2026

Map & Set

Key-value pairs and unique collections.

java
// Quick Reference
Map<String, Integer> m = new HashMap<>();
m.put("a", 1);  m.get("a");
Set<String> set = new HashSet<>();
set.add("x");   set.contains("x");
💡 HashMap keys are unique - putting an existing key overwrites its value.
⚡ getOrDefault and merge make counting and accumulation one-liners.
📌 HashMap/HashSet are unordered; use LinkedHashMap or TreeMap for ordering.
🟢 Iterate a Map via entrySet() to access keys and values together.
mapset

Continue with Java

Save the full cheat sheet or work through every related task.

More Java tasks

Back to the full Java cheat sheet