JVM / Java / Collections / Maps
1. Key-value pairs
The keys must be unique, values may be duplicates.
If we put() a value using a key that alreasy exists, the old value is overwritten.
Internaly HashMap uses hashing to store the items in buckets.
- hashCode(key) to finds the bucket
- equals(key) to resolve collisions (same bucket)
Keys must implement proper equals() and hashCode(), String already does.
Time Complexity:
- put() and get() are O(1) average time
- very fast for lookups by key
package collections.maps;
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
Map<String, Integer> scores = new HashMap<>();
scores.put("Mary", 10);
scores.put("Mary", 20);
scores.put("John", 20);
scores.put("Boby", 16);
System.out.println(scores);
System.out.println(scores.get("John"));
}
}
2. Map Iteration
We can iterate through keys, values pairs.
- keySet() -> iterate through keys only
- values() -> iterate through values only
- entrySet() -> iterate through key/value pairs
import java.util.HashMap;
import java.util.Map;
public class MapLoop {
public static void main(String[] args) {
Map<String, Integer> scores = Map.of(
"Mary", 10,
"John", 20,
"Boby", 16
);
scores = new HashMap<>();
scores.put("Mary", 10);
scores.put("John", 20);
scores.put("Boby", 16);
for (String key : scores.keySet()) {
System.out.println(key);
}
for (Integer value : scores.values()){
System.out.println(value);
}
for(Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
}