Map
A Map is a collection of key-value pairs. Each key is unique; each key maps to exactly one value. Use HashMap as the default implementation.
Common operations
Map<String, Integer> ages = new HashMap<>();
ages.put("Ada", 36);
ages.put("Grace", 85);
ages.get("Ada"); // 36
ages.getOrDefault("Unknown", 0); // 0
ages.containsKey("Grace"); // true
ages.remove("Ada");
ages.size(); // 1
// Iterate:
ages.forEach((k, v) -> System.out.println(k + " -> " + v));
Implementations
| Implementation | Order | Thread-safe? |
|---|---|---|
HashMap | Unordered | No |
LinkedHashMap | Insertion order | No |
TreeMap | Sorted by key | No |
ConcurrentHashMap | Unordered | Yes |
EnumMap | Enum order | No |
Immutable map (Java 9+)
Map<String, Integer> m = Map.of("a", 1, "b", 2, "c", 3);
Map<String, Integer> big = Map.ofEntries(
Map.entry("a", 1),
Map.entry("b", 2)
);
Map is not a Collection
Map does not extend Collection. Its entries, keys, and values are accessed via entrySet(), keySet(), values() — each returns a view that is a Collection.