CAP477 · Unit 4: Collections and functional Java
Map collections
8 practice questions
Key points
- put returns the old value
- TreeMap sorted, LinkedHashMap insertion order, HashMap unordered
- TreeMap and Hashtable reject null keys
- merge and computeIfAbsent for counting and grouping
A Map stores key-value pairs with unique keys (not part of Collection).
| Class | Order | Null key | Notes |
|---|---|---|---|
| HashMap | none | 1 null key, null values | O(1) average |
| LinkedHashMap | insertion order | yes | hash + linked list |
| TreeMap | sorted by key | no (NPE) | O(log n), firstKey, floorKey, headMap |
| Hashtable | none | no null key or value | legacy, synchronized |
Methods: put(k, v) returns the previous value (or null): put("a",1) gives null, then put("a",2) gives 1. get returns null if absent; getOrDefault, putIfAbsent, containsKey, containsValue, remove, size, keySet(), values(), entrySet(). Modern updates: merge(k, 1, Integer::sum) (counting), computeIfAbsent(k, f) (group into lists), compute, computeIfPresent (returning null removes), replaceAll.
Word count of "to be or not to be": TreeMap gives {be=2, not=1, or=1, to=2}; LinkedHashMap keeps first-seen order {to=2, be=2, or=1, not=1}.
Keys need equals and hashCode: with both overridden, two new K(1) keys are the same key (size 1, latest value 2).
Map.of(...) is immutable. Iterate with for (Map.Entry<K,V> e : m.entrySet()).
Exam pitfall: get returning null can mean "absent" or "mapped to null"; use containsKey to tell.
Try two questions
HashMap m = new HashMap(); m.put(null, 1); What happens?
- NullPointerException
- It works; HashMap allows one null key
- IllegalArgumentException
- The entry is ignored
Show the answer
B. Output of the null-key test: 1 null true (get(null), get("k"), containsKey("k")); TreeMap and Hashtable both threw NullPointerException.
Which call groups values into lists by key, creating the list when missing?
- map.merge(key, v)
- map.computeIfAbsent(key, k -> new ArrayList<>()).add(v)
- map.putIfPresent(key, v)
- map.group(key, v)
Show the answer
B. Result for a:1, a:2, b:3 is {a=[1, 2], b=[3]}.