HashMap
- Java course
- Beginner
- Lesson 67/116
- 5 min
Learn key-value mapping with HashMap.
Key-value: HashMap
A HashMap maps a key to a value. You use it when you need fast lookup from key to value, like a dictionary.
HashMap<String, Integer> ages = new HashMap<>();
ages.put("Ayşe", 28);
ages.put("Mehmet", 32);
int age = ages.get("Ayşe");
// age = 28Each key appears only once inside. If you call put again with the same key, the old value is overwritten. HashMap lives in the java.util package.
Looping over the key set
To walk every key of a HashMap, you use keySet. This method returns a Set view of the keys.
for (String name : ages.keySet()) {
System.out.println(name + " - " + ages.get(name));
}To walk pairs (key and value together), entrySet is more efficient because you skip the get call. Each item of entrySet is a Map.Entry.
Practice City temperature table
Create a HashMap<String, Integer>; set "İstanbul" to 14 and "Ankara" to 11. Then print the value of "İstanbul".
Starter code
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// Create a HashMap<String, Integer>
// İstanbul -> 14, Ankara -> 11
// Print the value of İstanbul
}
}Sample solution
HashMap<String, Integer> temps = new HashMap<>();
temps.put("İstanbul", 14);
temps.put("Ankara", 11);
System.out.println(temps.get("İstanbul"));Expected output
14
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens if you call put twice with the same key?
- The old value is overwritten
- The second value is ignored
- It throws an error
- Two equal keys are kept Correct answer
Explanation: Because keys are unique, the old value is lost.
2 Match method to purpose
| Term | Meaning |
|---|---|
put(k, v) |
Adds a key-value pair |
get(k) |
Returns the value of the key |
keySet() |
Returns the set of keys |
size() |
Returns the number of pairs |
3 Fill in the blank: get the value
HashMap<String, Integer> ages = new HashMap<>();
ages.put("Ayşe", 28);
int age = ages.____("Ayşe");
HashMap<String, Integer> ages = new HashMap<>();
ages.put("Ayşe", 28);
int age = ages.get("Ayşe");
Explanation: get("Ayşe") returns the value.