Skip to content

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.

Beginner 18 min read·Lesson 32 of 39 in Java Programming

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

Java
Set<String> seen = new HashSet<>();
boolean isNew = seen.add("x"); // false if already present
Map<String, Integer> count = new HashMap<>();
count.merge(word, 1, Integer::sum); // counting
int n = count.getOrDefault("java", 0);
Map<Character, List<String>> groups = new TreeMap<>();
groups.computeIfAbsent(w.charAt(0), k -> new ArrayList<>()).add(w);
for (Map.Entry<String, Integer> e : count.entrySet()) { e.getKey(); e.getValue(); }
  • 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

Java
import java.util.*;
public class Main {
public static void main(String[] args) {
Set<String> java = new TreeSet<>(List.of("Asha", "Ravi", "Meera", "John"));
Set<String> python = new TreeSet<>(List.of("Ravi", "Priya", "John", "Kiran"));
Set<String> both = new TreeSet<>(java);
both.retainAll(python);
Set<String> either = new TreeSet<>(java);
either.addAll(python);
Set<String> onlyJava = new TreeSet<>(java);
onlyJava.removeAll(python);
System.out.println("both: " + both + ", either: " + either.size() + ", only Java: " + onlyJava);
System.out.println("add duplicate Ravi: " + java.add("Ravi"));
TreeSet<Integer> slots = new TreeSet<>(List.of(9, 11, 14, 16));
System.out.println("next slot at or after 12: " + slots.ceiling(12) + ", last before 14: " + slots.lower(14) + ", first: " + slots.first());
}
}
Output
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

Java
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Integer> stock = new TreeMap<>();
stock.put("pen", 40);
stock.put("notebook", 25);
stock.put("eraser", 60);
Integer old = stock.put("pen", 35); // replace
System.out.println("pen was " + old + ", now " + stock.get("pen"));
System.out.println("stapler: " + stock.get("stapler") + " / " + stock.getOrDefault("stapler", 0));
stock.putIfAbsent("stapler", 5);
stock.remove("eraser");
for (Map.Entry<String, Integer> e : stock.entrySet())
System.out.println(" " + e.getKey() + " = " + e.getValue());
System.out.println("keys " + stock.keySet() + ", total items " + stock.values().stream().mapToInt(Integer::intValue).sum());
}
}
Output
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

Java
import java.util.*;
public class Main {
public static void main(String[] args) {
String text = "the quick brown fox jumps over the lazy dog the fox";
Map<String, Integer> freq = new HashMap<>();
for (String w : text.split(" ")) freq.merge(w, 1, Integer::sum);
List<Map.Entry<String, Integer>> top = new ArrayList<>(freq.entrySet());
top.sort(Map.Entry.<String, Integer>comparingByValue().reversed().thenComparing(Map.Entry.comparingByKey()));
System.out.println("top 3: " + top.subList(0, 3));
Map<Integer, List<String>> byLength = new TreeMap<>();
for (String w : new TreeSet<>(freq.keySet())) byLength.computeIfAbsent(w.length(), k -> new ArrayList<>()).add(w);
System.out.println("by length: " + byLength);
record Student(int roll, String name) { }
List<Student> students = List.of(new Student(101, "Asha"), new Student(102, "Ravi"), new Student(103, "Meera"));
Map<Integer, Student> byRoll = new HashMap<>();
for (Student s : students) byRoll.put(s.roll(), s);
System.out.println("roll 102: " + byRoll.get(102).name() + ", roll 999: " + byRoll.containsKey(999));
Map<String, String> cache = new LinkedHashMap<>(16, 0.75f, true) { // access order
@Override protected boolean removeEldestEntry(Map.Entry<String, String> eldest) { return size() > 3; }
};
for (String page : List.of("home", "about", "blog", "home", "shop")) cache.put(page, "<" + page + ">");
System.out.println("LRU cache keeps: " + cache.keySet());
}
}
Output
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.
  • computeIfAbsent groups 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; overriding removeEldestEntry evicts the least recently used entry once there are more than three.
  • After accessing home again and adding shop, the least recently used page, about, is evicted.

Expected output

Running “Counting, grouping, an index and an LRU cache” prints exactly:

TextOutput
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]

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

if (map.containsKey(w)) map.put(w, map.get(w) + 1); else map.put(w, 1);

Prefer

map.merge(w, 1, Integer::sum);

merge expresses the intent in one call and avoids two lookups and possible null mistakes.

Relying on HashMap order

Avoid

Map<String, Integer> m = new HashMap<>(); // expecting insertion order

Prefer

Map<String, Integer> m = new LinkedHashMap<>(); // or TreeMap for sorted keys

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

  1. 1
    Find the first non-repeating character in a string using a LinkedHashMap.
  2. 2
    Group 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?
Practise this topic