Module 9 · Collections and Generics — topic 3 of 5
Sets and Maps
HashSet, LinkedHashSet and TreeSet; HashMap, LinkedHashMap and TreeMap; counting, grouping and caching patterns with getOrDefault, merge and computeIfAbsent; and how hashing works.
Learning objectives
- Choose between hash, linked and tree sets and maps
- Use getOrDefault, merge, computeIfAbsent and entrySet idiomatically
- Explain how HashMap stores and finds entries
Definition
A Set is a collection without duplicates, determined by equals (and hashCode for hash-based sets). A Map associates unique keys with values; it offers fast lookup of a value by its key.
Introduction
'Have I seen this before?' and 'what is the value for this key?' are two of the most common questions programs ask. Sets answer the first and maps the second — in constant time for hash-based versions, which is why they appear in nearly every real application and interview solution.
Why it matters
Counting word frequencies, grouping records, caching results and indexing data by id are all map problems.
Knowing how HashMap works internally is a classic interview topic.
Detailed explanation
HashSet / HashMap use the element's (or key's) hashCode to choose a *bucket* and equals to find the exact match inside it. Lookups, insertions and removals are O(1) on average. Iteration order is unspecified. When a bucket gets crowded (8+ entries), Java 8+ turns it into a balanced tree, so the worst case is O(log n).
LinkedHashSet / LinkedHashMap also keep a linked list of entries, preserving insertion order (or access order, which is handy for LRU caches).
TreeSet / TreeMap keep elements sorted (natural order or a Comparator) in a red-black tree: O(log n) operations plus navigation methods — first, last, floor, ceiling, headSet, tailMap.
Map basics. put(k, v) adds or replaces (returning the old value), get(k) returns the value or null, containsKey, remove, size, keySet(), values() and entrySet().
Modern map methods (Java 8). getOrDefault(k, d); putIfAbsent; merge(k, v, fn) for counting (merge(word, 1, Integer::sum)); computeIfAbsent(k, f) for grouping (computeIfAbsent(key, k -> new ArrayList<>()).add(x)).
Iterating a map. Loop over entrySet() to get keys and values together: for (Map.Entry<String, Integer> e : map.entrySet()).
Set operations. addAll (union), retainAll (intersection) and removeAll (difference) — on copies if you want to keep the originals.
Syntax
- Keys must have consistent equals and hashCode (or compareTo for Tree maps).
- HashMap allows one null key; TreeMap does not (with natural ordering).
- Don't modify keys after inserting them.
Code examples
Set operations and TreeSet navigation
both: [John, Ravi], either: 6, only Java: [Asha, Meera] add duplicate Ravi: false next slot at or after 12: 14, last before 14: 11, first: 9
Map basics
pen was 40, now 35 stapler: null / 0 notebook = 25 pen = 35 stapler = 5 keys [notebook, pen, stapler], total items 65
More examples
Counting, grouping, an index and an LRU cache
top 3: [the=3, fox=2, brown=1]
by length: {3=[dog, fox, the], 4=[lazy, over], 5=[brown, jumps, quick]}
roll 102: Ravi, roll 999: false
LRU cache keeps: [blog, home, shop]Step-by-step explanation
merge(w, 1, Integer::sum)counts every word; the entries are then copied into a list and sorted by count (descending) and then by word, so ties are deterministic.computeIfAbsentgroups the distinct words by length; iterating a TreeSet first keeps each group alphabetical, and the TreeMap sorts the lengths.- A map from roll number to Student is an index: looking a student up by roll is O(1) instead of scanning the list.
new LinkedHashMap<>(16, 0.75f, true)orders entries by most recent access; overridingremoveEldestEntryevicts the least recently used entry once there are more than three.- After accessing
homeagain and addingshop, the least recently used page,about, is evicted.
Expected output
Running “Counting, grouping, an index and an LRU cache” prints exactly:
Practical applications
- Word counts and analytics dashboards
- Looking up users, products or orders by id
- Grouping transactions by date or category
- Caches and de-duplication of events
Best practices
- Use merge for counting and computeIfAbsent for grouping.
- Iterate entrySet when you need both key and value.
- Choose TreeMap/TreeSet when you need sorted data or range queries.
Common mistakes
Counting with containsKey and get
Avoid
Prefer
merge expresses the intent in one call and avoids two lookups and possible null mistakes.
Relying on HashMap order
Avoid
Prefer
HashMap's iteration order is unspecified and can change; choose the map that guarantees the order you need.
Important notes
- A HashMap's default capacity is 16 with a load factor of 0.75; it doubles when 75% full.
- Map.of supports up to 10 key-value pairs; use Map.ofEntries or a HashMap for more.
Key takeaways
- Sets reject duplicates; maps map unique keys to values.
- Hash versions are fastest; Linked keeps insertion order; Tree keeps sorted order.
- getOrDefault, merge and computeIfAbsent make common map patterns short and safe.
Try it yourself
- 1Find the first non-repeating character in a string using a LinkedHashMap.
- 2Group a list of employees by department into a Map<String, List<String>>.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
8 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is printed?
- BeginnerWhat is printed?
- ModerateWhat is printed?