A map stores key-value pairs.
Each key is unique, but values can be duplicated.

Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);

Common Implementation

ImplementationKey Features
HashMapFast, no ordering, allows 1 null key
LinkedHashMapMaintains insertion order
TreeMapSorted by keys (natural or custom order)
HashtableLegacy, synchronized, no null keys
ConcurrentHashMapThread-safe, no locking entire map

Methods

map.put("X", 100);
map.get("X");            // 100
map.containsKey("X");    // true
map.containsValue(100);  // true
map.remove("X");
map.size();
map.clear();

Iterating over a Map

for (Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + " = " + entry.getValue());
}

Comparison

HashMap vs TreeMap vs LinkedHashMap

FeatureHashMapLinkedHashMapTreeMap
Order✗ None✅ Insertion order✅ Sorted by key
Null Keys✅ One null key✅ One null key
Performance✅ FastestSlightly slowerSlowest
Thread-safe

Key Notes

  • Map is not a subtype of Collection.
  • Use equals() and hashCode()for key comparison.
  • For thread-safe use: prefer ConcurrentHashMap over Hashtable.

Tip

Be ready to:

  • explain how keys are compared,
  • compare HashMap vs TreeMap vs LinkedHashMap,
  • write code using entrySet() loop,
  • mention null-handling rules for keys & values.

Parent: _Collections