Java Notes
Learn Java HashMap — storing key-value pairs, all essential methods, iterating entries, handling duplicate keys, getOrDefault, merge, computeIfAbsent, and common mistakes.
HashMap stores key-value pairs. Every key maps to exactly one value. Keys must be unique — adding the same key again replaces the old value. Values can repeat. Order is not guaranteed.
This is the most commonly used Map in Java. Use it whenever you need to look up a value by a key — word counts, user lookup tables, configuration, caching.
Creating and Using HashMap
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Line by line:
scores.put("Asha", 95)with existing key — updates the value. Returns the old value (92).scores.get("Dev")— key does not exist → returnsnull.remove("Ravi")— removes the key-value pair. Returns the removed value (78).
Iterating a HashMap
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Useful Methods: getOrDefault, putIfAbsent, merge, computeIfAbsent
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Line by line:
getOrDefault(word, 0)— returns 0 if word is not in the map (instead ofnull). Common pattern for frequency counting.putIfAbsent("apple", 99)— apple already exists with 3, so 99 is ignored.merge("Asha", 5, Integer::sum)— old value (10) + new value (5) using sum function = 15.
HashMap Allows One null Key
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
HashMap allows one null key and multiple null values. Hashtable and TreeMap do not allow null keys.
Common Mistake 1: Assuming Order
Map<String, Integer> map = new HashMap<>();
map.put("c", 3);
map.put("a", 1);
map.put("b", 2);
System.out.println(map); // order NOT guaranteed — could be {a=1, b=2, c=3} or anything
// If you need sorted keys:
// Use TreeMap
// If you need insertion order:
// Use LinkedHashMapCommon Mistake 2: Using get() Without Null Check
Map<String, Integer> map = new HashMap<>();
int count = map.get("apple"); // NullPointerException — key not found, returns null
// null cannot be unboxed to int
// CORRECT
int count = map.getOrDefault("apple", 0);
// or
Integer val = map.get("apple");
if (val != null) { int count2 = val; }Common Mistake 3: Modifying While Iterating
Map<String, Integer> map = new HashMap<>();
map.put("a", 1); map.put("b", 2); map.put("c", 3);
// WRONG — ConcurrentModificationException
// for (String key : map.keySet()) {
// if (map.get(key) < 2) map.remove(key);
// }
// CORRECT — remove using iterator
map.entrySet().removeIf(e -> e.getValue() < 2);
System.out.println(map); // {b=2, c=3}Practice Task
Task: Given an array of exam scores: {"Asha", 92, "Ravi", 78, "Priya", 92, "Dev", 65, "Asha", 88} — alternating name and score (treat Asha's second score as an update). Use a HashMap<String, Integer> to:
- Store each student's latest score
- Find the student with the highest score
- Count how many students scored above 80
Hint: Iterate the array in steps of 2. For max, loop over entrySet(). For count, use values() with a counter.
Solution:
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
What to observe: Asha's first score (92) gets replaced by 88. The final map has 4 entries (not 5). Iterating values() gives only the scores without keys — useful when you only need the values.
Continue the lesson path