Map<K,V>
- Java course
- Intermediate
- Lesson 89/116
- 5 min
Learn generic maps with Map<K,V>.
The Map<K,V> interface
Map<K,V> stores key-value pairs; K is the key type and V is the value type. Map<String, Integer> ages = new HashMap<>(); keeps integer values under string keys.
The most common concrete implementation is HashMap. put(key, value) adds a new pair or updates an existing one; get(key) returns the value, or null if the key is absent. Keys are unique; a second put with the same key overwrites the old value.
A dictionary with HashMap
A HashMap behaves like a dictionary: the key is the word, the value is the entry. ages.put("Ayşe", 30); adds a record; ages.get("Ayşe") gives you 30.
ages.containsKey("Veli") checks whether the key exists; it returns false if not. ages.size() tells how many pairs exist. for (String k : ages.keySet()) walks all keys.
Practice Build an age dictionary
Declare Map<String, Integer> ages = new HashMap<>();. Add two records with ages.put("Ayşe", 30); and ages.put("Alex", 25);. Print Ayşe's age with System.out.println(ages.get("Ayşe")); and the pair count with System.out.println(ages.size());.
Starter code
import java.util.Map;
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// Declare Map<String, Integer>, add two pairs, print value and count
}
}Sample solution
import java.util.Map;
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
Map<String, Integer> ages = new HashMap<>();
ages.put("Ayşe", 30);
ages.put("Alex", 25);
System.out.println(ages.get("Ayşe"));
System.out.println(ages.size());
}
}Expected output
30 2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the Map methods
| Term | Meaning |
|---|---|
put(k, v) |
Adds a key-value pair |
get(k) |
Returns the value |
containsKey(k) |
Checks if key exists |
keySet() |
Returns all keys |
2 Complete the age-adding call
ages.____("Ayşe", 30);
ages.put("Ayşe", 30);
Explanation: The put method adds the key-value pair.
3 What does a second put with the same key do?
- Ignores the second pair
- Throws an error
- Overwrites the old value Correct answer
- Generates a new key
Explanation: A second put with the same key overwrites the old value.