Map
A value by key
Map<K, V> stores key-value pairs.
A key acts as an identifier: it lets you access the associated value directly,
without working through positions as you would in a list.
Map<String, Integer> scores = new HashMap<>();
scores.put("Ann", 90);
scores.put("Bob", 75);
System.out.println(scores.get("Ann")); // 90
The first type parameter is the key type, and the second is the value type.
Keys in a map are unique: another put() with the same key replaces the old value.
Values may repeat.
Reading and checking
get(key) returns the value or null if there is no matching entry.
When you need a fallback result, getOrDefault() is convenient.
Map<String, Integer> attempts = new HashMap<>();
attempts.put("login", 2);
int loginAttempts = attempts.getOrDefault("login", 0);
int paymentAttempts = attempts.getOrDefault("payment", 0);
System.out.println(loginAttempts); // 2
System.out.println(paymentAttempts); // 0
There are separate checks with containsKey() and containsValue().
In practice, lookup by key is usually the central map operation.
Traversing entries
A map can expose a set of keys, a collection of values, or a set of entries through
keySet(), values(), and entrySet().
If you need both the key and the value, working with entries is more convenient.
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
Map defines the general key-based model.
How an implementation organizes fast lookup depends on the concrete class — next, we will study HashMap separately.