Collections Framework · Lesson 32 of 42
Sets and Maps: HashSet, HashMap, TreeMap
A Set keeps unique items. A Map stores key → value pairs: roll number → student, product code → price, word → count. HashMap is probably the most important class in the whole library, and "How does HashMap work internally?" is asked in nearly every Java interview.
In this lesson
- HashSet, LinkedHashSet and TreeSet
- HashMap methods: put, get, getOrDefault, merge, entrySet
- LinkedHashMap and TreeMap ordering
- How HashMap works inside
Sets
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
List<String> visits = List.of("ravi", "asha", "ravi", "zoya", "asha", "ben");
Set<String> hash = new HashSet<>(visits);
Set<String> linked = new LinkedHashSet<>(visits);
Set<String> tree = new TreeSet<>(visits);
System.out.println("unique visitors: " + hash.size());
System.out.println("insertion order: " + linked);
System.out.println("sorted: " + tree);
System.out.println(hash.add("ravi") + " " + hash.contains("zoya")); // add returns false for duplicates
Set<Integer> a = new TreeSet<>(List.of(1, 2, 3, 4));
Set<Integer> b = new TreeSet<>(List.of(3, 4, 5));
Set<Integer> common = new TreeSet<>(a);
common.retainAll(b); // intersection
Set<Integer> all = new TreeSet<>(a);
all.addAll(b); // union
System.out.println(common + " " + all);
}
}
unique visitors: 4 insertion order: [ravi, asha, zoya, ben] sorted: [asha, ben, ravi, zoya] false true [3, 4] [1, 2, 3, 4, 5]
| Set | Order | add / contains |
|---|---|---|
HashSet | none guaranteed | O(1) |
LinkedHashSet | insertion order | O(1) |
TreeSet | sorted | O(log n) |
HashMap
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Integer> stock = new HashMap<>();
stock.put("pens", 40);
stock.put("notebooks", 12);
stock.put("pens", 35); // same key: value replaced
System.out.println(stock.get("pens"));
System.out.println(stock.get("erasers")); // missing → null
System.out.println(stock.getOrDefault("erasers", 0));
System.out.println(stock.containsKey("notebooks") + " " + stock.size());
stock.putIfAbsent("erasers", 50);
stock.remove("notebooks");
for (Map.Entry<String, Integer> e : stock.entrySet()) {
System.out.println(e.getKey() + " → " + e.getValue());
}
}
}
35 null 0 true 2 erasers → 50 pens → 35
Common mistake: relying on HashMap order
HashMap gives no ordering guarantee – the order you see can change as the map grows or between Java versions. Use LinkedHashMap for insertion order or TreeMap for sorted keys.
Counting and grouping patterns
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
String text = "the cat and the hat and the bat";
Map<String, Integer> counts = new TreeMap<>();
for (String w : text.split(" ")) counts.merge(w, 1, Integer::sum); // count
System.out.println(counts);
String[][] staff = {{"Asha", "IT"}, {"Ben", "HR"}, {"Chen", "IT"}, {"Dia", "Sales"}};
Map<String, List<String>> byDept = new TreeMap<>();
for (String[] s : staff) byDept.computeIfAbsent(s[1], k -> new ArrayList<>()).add(s[0]); // group
System.out.println(byDept);
}
}
{and=2, bat=1, cat=1, hat=1, the=3}
{HR=[Ben], IT=[Asha, Chen], Sales=[Dia]}merge(key, 1, Integer::sum) means "put 1, or add 1 to the existing value". computeIfAbsent creates the list the first time a key is seen. These two methods replace a lot of if (!map.containsKey(...)) code.
TreeMap: sorted keys with navigation
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
TreeMap<Integer, String> grades = new TreeMap<>();
grades.put(90, "A+");
grades.put(75, "A");
grades.put(60, "B");
grades.put(40, "C");
grades.put(0, "Fail");
for (int marks : new int[]{82, 59, 95, 12}) {
System.out.println(marks + " → " + grades.floorEntry(marks).getValue()); // largest key ≤ marks
}
System.out.println(grades.firstKey() + " " + grades.lastKey() + " " + grades.headMap(60));
}
}
82 → A
59 → C
95 → A+
12 → Fail
0 90 {0=Fail, 40=C}How HashMap works inside
map.put("pens", 40)
- hashCode()"pens".hashCode() → an int
- Bucket indexspread the hash, then (n − 1) & hash → one of n buckets
- Bucket empty?store a new node (key, value, hash)
- Collisionwalk the bucket; equals() true → replace value, else append
- Too full?size > 0.75 × capacity → double the table and redistribute
- Default capacity 16, load factor 0.75 – so the table doubles when the 13th entry is added.
- Each bucket is a linked list; since Java 8 a bucket with more than 8 entries becomes a balanced tree, so worst-case lookups are O(log n) instead of O(n).
- One
nullkey is allowed (it goes to bucket 0).HashtableandConcurrentHashMapdon't allow null keys. - This is why keys need correct
equals()andhashCode()(chapter 9) and should be immutable.
Interview angle
HashMap is not thread-safe. For shared maps use ConcurrentHashMap, which locks only small parts of the table, rather than the legacy Hashtable or Collections.synchronizedMap.
Practice
Try it yourself
Find the first repeated character in "programming" using a Set.
Show solution
import java.util.HashSet; import java.util.Set; public class Main { public static void main(String[] args) { Set<Character> seen = new HashSet<>(); for (char c : "programming".toCharArray()) { if (!seen.add(c)) { System.out.println(c); break; } } } }r
Given marks {Ravi=72, Sana=91, Tom=85}, print the topper.
Show solution
import java.util.Map; public class Main { public static void main(String[] args) { Map<String, Integer> marks = Map.of("Ravi", 72, "Sana", 91, "Tom", 85); String top = null; for (var e : marks.entrySet()) { if (top == null || e.getValue() > marks.get(top)) top = e.getKey(); } System.out.println(top + " " + marks.get(top)); } }Sana 91
Quick check
What happens when you put a key that already exists?
The old value is replaced (put returns the old value).
Which map keeps keys sorted?
TreeMap
When does a HashMap resize?
When its size exceeds capacity × load factor (16 × 0.75 = 12 by default); the table then doubles.
Summary
- HashSet/HashMap: O(1), no order; Linked versions keep insertion order; Tree versions sort.
- Use getOrDefault, merge and computeIfAbsent for counting and grouping.
- HashMap hashes keys into buckets, resolves collisions with equals(), resizes at 75% and treeifies big buckets.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.