A map is a labelled box
A HashMap<K, V> stores key → value pairs, like a phone book: a name (key) leads to a number (value). Each key appears once.
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, Integer> price = new HashMap<String, Integer>();
price.put("tea", 20);
price.put("coffee", 35);
price.put("tea", 25); // same key: the value is replaced
System.out.println(price.get("tea"));
System.out.println(price.containsKey("juice"));
System.out.println(price.get("juice")); // missing key gives null
System.out.println(price.getOrDefault("juice", 0)); // or a default you choose
System.out.println(price.size());
}
}Output
25 false null 0 2
The counting pattern
The most common use of a map in DSA: how many times does each thing appear?
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
HashMap<String, Integer> votes = new HashMap<String, Integer>();
for (int i = 0; i < n; i++) {
String name = sc.next();
votes.put(name, votes.getOrDefault(name, 0) + 1);
}
// A HashMap has no useful order, so copy into a TreeMap to print a-z
TreeMap<String, Integer> sorted = new TreeMap<String, Integer>(votes);
for (Map.Entry<String, Integer> e : sorted.entrySet()) {
System.out.println(e.getKey() + " " + e.getValue());
}
}
}Input (what the user types)
7 mango apple mango kiwi apple mango kiwi
Output
apple 2 kiwi 2 mango 3
Common mistake: Printing a
HashMapdirectly and expecting an order. Its order depends on the hash buckets and can look random. When order matters, use aTreeMap(keys sorted) or sort the keys yourself.
| Map | Order of keys | get / put |
|---|---|---|
HashMap | no useful order | O(1) on average |
TreeMap | sorted | O(log n) (Module 13) |