R
Rishtaara
Java Fundamentals
Lesson 30 of 36Article16 min

Map, HashMap, TreeMap & LinkedHashMap

Map stores keys mapped to values. Keys must be unique. put, get, remove, containsKey.

Map — key-value pairs

Map stores keys mapped to values. Keys must be unique. put, get, remove, containsKey.

Use when you need fast lookup by ID, email, or name.

Real-life example: Map is a phone contact book — name (key) → number (value). Search name, get number instantly.

HashMap basics
import java.util.*;

Map<String, Integer> scores = new HashMap<>();
scores.put("Asha", 91);
scores.put("Rohan", 88);
System.out.println(scores.get("Asha")); // 91

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

HashMap, TreeMap & LinkedHashMap

HashMap — fastest, no order. TreeMap — keys sorted. LinkedHashMap — insertion order of keys.

Choose based on whether you need sorted keys or stable iteration order.

Real-life example: TreeMap is a dictionary sorted A–Z. LinkedHashMap remembers the order you added words.

TreeMap and LinkedHashMap
Map<String, String> tree = new TreeMap<>();
tree.put("zebra", "Z");
tree.put("apple", "A");
System.out.println(tree.keySet()); // [apple, zebra]

Map<String, String> linked = new LinkedHashMap<>();
linked.put("first", "1");
linked.put("second", "2");