1. University MCA (AI/ML) Semester 2
  2. CAP477
  3. Unit 4

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).

ClassOrderNull keyNotes
HashMapnone1 null key, null valuesO(1) average
LinkedHashMapinsertion orderyeshash + linked list
TreeMapsorted by keyno (NPE)O(log n), firstKey, floorKey, headMap
Hashtablenoneno null key or valuelegacy, 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

Question 1 · Tier 3, Apply

HashMap m = new HashMap(); m.put(null, 1); What happens?

  1. NullPointerException
  2. It works; HashMap allows one null key
  3. IllegalArgumentException
  4. 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.

Question 2 · Tier 3, Apply

Which call groups values into lists by key, creating the list when missing?

  1. map.merge(key, v)
  2. map.computeIfAbsent(key, k -> new ArrayList<>()).add(v)
  3. map.putIfPresent(key, v)
  4. map.group(key, v)
Show the answer

B. Result for a:1, a:2, b:3 is {a=[1, 2], b=[3]}.