Store data as key-value pairs.
import java.util.HashMap;
HashMap<String, Integer> ages = new HashMap<>();
HashMap<String, Integer> map = new HashMap<>();
map.put("Alice", 25); // Add entry
map.put("Bob", 30);
map.get("Alice"); // Get value: 25
map.remove("Bob"); // Remove entry
map.containsKey("Alice"); // true
map.containsValue(25); // true
map.size(); // Number of entries
// Loop through keys
for (String key : map.keySet()) {
System.out.println(key);
}
// Loop through key-value pairs
for (var entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
| key | value |
|---|---|
| Alice | 95 |
| Bob | 87 |
| Charlie | 92 |
Interactive Visualization