Java Collections
HashSet / TreeSet
Complete lesson for HashSet / TreeSet using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.
Basics — HashSet / TreeSet
Section: Java Collections. HashSet stores unique elements with super-fast lookups. Learn adding, checking, removing, set operations, custom objects with equals and hashCode, LinkedHashSet, TreeSet, internals, and pitfalls — all with real-life examples.
What is HashSet?
HashSetis aSetimplementation injava.utilthat stores only unique elements. Adding an element that is already present is simply ignored.- It does not keep any order and has no index, but
add,contains, andremovetake O(1) time on average, even with millions of elements. addreturnstruewhen the element is new andfalsewhen it is a duplicate — perfect for "has this happened before?" checks.- Real life: a polling booth. Each voter ID can vote only once; the officer instantly knows if an ID has already voted.
import java.util.HashSet;
import java.util.Set;
public class PollingBooth {
public static void main(String[] args) {
Set<String> voted = new HashSet<>();
String[] queue = { "VOTER101", "VOTER205", "VOTER101", "VOTER333", "VOTER205" };
for (String id : queue) {
if (voted.add(id)) { // false if already present
System.out.println(id + " voted");
} else {
System.out.println(id + " already voted - rejected");
}
}
System.out.println("Total valid votes: " + voted.size()); // 3
}
} Real-life examples of HashSet
| Real-life scenario | What the set stores | Why a HashSet |
|---|---|---|
| Polling booth | Voter IDs that have voted | One vote per person, instant check |
| Wedding or event entry | Scanned QR pass codes | Stops the same pass entering twice |
| Website analytics | Visitor IDs for the day | Count each visitor once |
| Social media post | Hashtags | #java appears only once |
| Library | Book IDs currently issued | Fast "is this book out?" check |
| Online shopping wishlist | Product IDs | Adding the same product again changes nothing |
| Email spam filter | Blocked words or senders | O(1) lookup for every word |
| Exam hall attendance | Roll numbers present | No double marking |
| Lottery draw | Numbers already drawn | No number is drawn twice |
| Payment gateway | Processed transaction IDs | Prevents charging a customer twice |
Features of HashSet
| Feature | Meaning |
|---|---|
| Unique elements | Duplicates are ignored (decided by equals and hashCode) |
| No order | Iteration order is unpredictable and can change as the set grows |
| No index | No get(i); you check membership with contains |
| null | One null element allowed |
| Speed | Average O(1) for add, contains, remove |
| Backed by | An internal HashMap (elements are the keys) |
| Defaults | Capacity 16, load factor 0.75 |
| Thread-safe | No |
| Iterator | Fail-fast |
| Interfaces | Set, Collection, Iterable, Cloneable, Serializable |
Creating a HashSet
| Constructor | Meaning |
|---|---|
new HashSet<>() | Empty set, capacity 16, load factor 0.75 |
new HashSet<>(int capacity) | Empty set with a given starting capacity |
new HashSet<>(int capacity, float loadFactor) | Custom capacity and load factor |
new HashSet<>(Collection c) | Copy of a collection; duplicates are dropped |
HashSet.newHashSet(int n) (Java 19) | Sized to hold n elements without resizing |
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class CreateHashSet {
public static void main(String[] args) {
Set<String> a = new HashSet<>(); // default
Set<String> b = new HashSet<>(100); // expecting ~75 elements
Set<String> c = new HashSet<>(64, 0.5f); // custom load factor
Set<String> d = new HashSet<>(List.of("red", "green", "red")); // duplicates dropped
Set<String> e = HashSet.newHashSet(1000); // Java 19: room for 1000
a.add("x");
System.out.println(a.size() + " " + b.size() + " " + c.size() + " " + d.size() + " " + e.size());
// 1 0 0 2 0
}
} HashSet methods
| Method | What it does | Real-life use |
|---|---|---|
add(e) | Adds if absent; returns true if added, false if duplicate | Register an email for a workshop |
addAll(c) | Adds all elements (union) | Merge two guest lists |
contains(o) | True if the element exists | Is this voter ID already used? |
containsAll(c) | True if all elements exist (subset check) | Does the candidate have all required skills? |
remove(o) | Removes the element; returns true if it was present | Cancel a registration |
removeAll(c) | Removes elements found in c (difference) | Remove unsubscribed emails |
retainAll(c) | Keeps only elements also in c (intersection) | Students in both clubs |
removeIf(predicate) | Removes elements matching a condition | Remove all test accounts |
size() / isEmpty() | Count / empty check | How many unique visitors? |
clear() | Removes everything | Reset at midnight |
iterator() / forEach(action) | Loop over elements (no fixed order) | Send a mail to every subscriber |
stream() | Filter, map, collect | Find all Gmail users |
toArray(new T[0]) | Copy into an array | Pass IDs to an old API |
Adding, checking, and removing elements
- Use the boolean result of
addto detect duplicates,containsto check membership, andremoveorremoveIfto delete. - Real life: registrations for a free coding workshop — each email can register once, entry is allowed only for registered emails, and cancellations are removed.
import java.util.HashSet;
import java.util.Set;
public class Workshop {
public static void main(String[] args) {
Set<String> registered = new HashSet<>();
registered.add("asha@gmail.com");
registered.add("ravi@yahoo.com");
registered.add("kiran@gmail.com");
boolean again = registered.add("asha@gmail.com"); // duplicate registration
System.out.println("Added again? " + again); // false
System.out.println("Seats taken: " + registered.size()); // 3
System.out.println(registered.contains("ravi@yahoo.com")); // true: allow entry
registered.remove("kiran@gmail.com"); // cancelled
registered.removeIf(email -> email.endsWith("@yahoo.com")); // remove a whole domain
System.out.println(registered); // [asha@gmail.com]
}
} Set operations: union, intersection, difference
- Sets support the same operations you learned in maths, using
addAll,retainAll,removeAll, andcontainsAll. - These methods change the set they are called on, so copy first if you need to keep the original.
| Operation | Maths | Java | Real life |
|---|---|---|---|
| Union | A ∪ B | copy.addAll(b) | Students in cricket OR football club |
| Intersection | A ∩ B | copy.retainAll(b) | Students in BOTH clubs |
| Difference | A − B | copy.removeAll(b) | Students only in cricket |
| Symmetric difference | (A ∪ B) − (A ∩ B) | union, then removeAll(intersection) | Students in exactly one club |
| Subset | B ⊆ A | a.containsAll(b) | Does the team have all required players? |
import java.util.Set;
import java.util.TreeSet;
public class ClubMembers {
public static void main(String[] args) {
Set<String> cricket = Set.of("Asha", "Ravi", "Kiran", "Meena");
Set<String> football = Set.of("Ravi", "John", "Meena", "Sita");
Set<String> union = new TreeSet<>(cricket); // TreeSet only to print sorted
union.addAll(football);
System.out.println("Any club: " + union); // [Asha, John, Kiran, Meena, Ravi, Sita]
Set<String> both = new TreeSet<>(cricket);
both.retainAll(football);
System.out.println("Both clubs: " + both); // [Meena, Ravi]
Set<String> onlyCricket = new TreeSet<>(cricket);
onlyCricket.removeAll(football);
System.out.println("Only cricket: " + onlyCricket); // [Asha, Kiran]
Set<String> exactlyOne = new TreeSet<>(union);
exactlyOne.removeAll(both);
System.out.println("Exactly one club: " + exactlyOne); // [Asha, John, Kiran, Sita]
System.out.println(cricket.containsAll(Set.of("Asha", "Ravi"))); // true: subset
}
} Iterating a HashSet
- Use for-each, an
Iterator(to remove while looping), orforEachwith a lambda. There is no index-based loop. - Never rely on the printed order of a HashSet. If you need order, copy into a list and sort, or use
LinkedHashSetorTreeSet. - Real life: hashtags on a post — you show each once, remove short ones, and sort them for display.
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
public class IterateTags {
public static void main(String[] args) {
Set<String> tags = new HashSet<>(List.of("java", "spring", "dsa", "sql", "react"));
for (String t : tags) { // order is NOT guaranteed
System.out.print("#" + t + " ");
}
System.out.println();
Iterator<String> it = tags.iterator(); // safe removal while looping
while (it.hasNext()) {
if (it.next().length() <= 3) it.remove(); // drops dsa and sql
}
tags.forEach(t -> System.out.print(t.toUpperCase() + " "));
System.out.println();
List<String> sorted = new ArrayList<>(tags); // need order? copy and sort
Collections.sort(sorted);
System.out.println(sorted); // [java, react, spring]
}
} Removing duplicates from a list
new HashSet<>(list)removes duplicates instantly but loses order.new LinkedHashSet<>(list)removes duplicates and keeps first-seen order.- Normalise values first (for example
toLowerCase()) when "Asha@Gmail.com" and "asha@gmail.com" should count as the same. - Real life: cleaning a newsletter mailing list where people signed up several times.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public class MailingList {
public static void main(String[] args) {
List<String> signups = List.of("asha@gmail.com", "ravi@yahoo.com", "asha@gmail.com",
"Kiran@Gmail.com", "kiran@gmail.com");
Set<String> unique = new HashSet<>(signups);
System.out.println("Exact unique: " + unique.size()); // 4 (case differs)
Set<String> cleaned = new LinkedHashSet<>();
for (String email : signups) {
cleaned.add(email.toLowerCase()); // normalise first
}
List<String> mailingList = new ArrayList<>(cleaned);
System.out.println(mailingList); // [asha@gmail.com, ravi@yahoo.com, kiran@gmail.com]
}
} HashSet with custom objects
- For your own classes, HashSet decides duplicates using
hashCode()(to find the bucket) andequals()(to compare). Override both, using the same fields. - If you forget, two objects with the same data are treated as different, and duplicates slip in.
- Java records generate
equalsandhashCodeautomatically:record Vehicle(String plate, String type) { }. - Real life: a toll plaza counting unique vehicles by number plate. The same car on a return trip must not be counted twice.
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
class Vehicle {
private final String plate;
private final String type;
Vehicle(String plate, String type) {
this.plate = plate;
this.type = type;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Vehicle v)) return false;
return plate.equals(v.plate); // same number plate = same vehicle
}
@Override
public int hashCode() {
return Objects.hash(plate); // same field as equals
}
@Override
public String toString() {
return plate + " (" + type + ")";
}
}
public class TollPlaza {
public static void main(String[] args) {
Set<Vehicle> passedToday = new HashSet<>();
passedToday.add(new Vehicle("TS09AB1234", "Car"));
passedToday.add(new Vehicle("AP28CD5678", "Truck"));
passedToday.add(new Vehicle("TS09AB1234", "Car")); // same car, return trip
System.out.println("Unique vehicles: " + passedToday.size()); // 2
System.out.println(passedToday.contains(new Vehicle("AP28CD5678", "Truck"))); // true
// Without equals and hashCode: size would be 3 and contains would be false
}
} Differences between HashSet, LinkedHashSet, and TreeSet
| Point | HashSet | LinkedHashSet | TreeSet |
|---|---|---|---|
| Order | None (unpredictable) | Insertion order | Sorted (natural or Comparator) |
| Internal structure | Hash table | Hash table + doubly linked list | Red-black tree |
| add / contains / remove | O(1) average | O(1) average | O(log n) |
| null | One allowed | One allowed | Not allowed (natural order) |
| Duplicates decided by | equals + hashCode | equals + hashCode | compareTo or compare |
| Memory | Least | A bit more (links) | More (tree nodes) |
| Extra methods | None | Java 21: getFirst, getLast, reversed | first, last, floor, ceiling, headSet, tailSet |
| Thread-safe | No | No | No |
| Use when | Fast membership checks | Unique + remember arrival order | Unique + always sorted or range queries |
| Real life | A bag of unique tokens | Guests in order of arrival | Names in a dictionary |
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class ThreeSets {
public static void main(String[] args) {
List<String> arrivals = List.of("Ravi", "Asha", "Meena", "Kiran", "Asha");
Set<String> hash = new HashSet<>(arrivals);
Set<String> linked = new LinkedHashSet<>(arrivals);
Set<String> tree = new TreeSet<>(arrivals);
System.out.println("HashSet: " + hash); // order depends on hash codes
System.out.println("LinkedHashSet: " + linked); // [Ravi, Asha, Meena, Kiran] (arrival order)
System.out.println("TreeSet: " + tree); // [Asha, Kiran, Meena, Ravi] (sorted)
}
} LinkedHashSet: unique with insertion order
LinkedHashSetis a HashSet that also remembers the order in which elements were first added. Re-adding an element does not move it.- It is ideal when you need uniqueness and a predictable, human-friendly order.
- Real life: a travel diary of cities visited on a road trip. Visiting Pune twice still lists it once, at its first visit.
import java.util.LinkedHashSet;
import java.util.Set;
public class RoadTrip {
public static void main(String[] args) {
String[] route = { "Hyderabad", "Pune", "Mumbai", "Pune", "Goa", "Hyderabad" };
Set<String> visited = new LinkedHashSet<>();
for (String city : route) {
visited.add(city);
}
System.out.println("Cities visited: " + visited); // [Hyderabad, Pune, Mumbai, Goa]
System.out.println("Stops: " + route.length + ", unique cities: " + visited.size()); // 6, 4
}
} TreeSet: unique and sorted
TreeSetkeeps elements sorted at all times and offers navigation methods to find the nearest, smallest, or largest elements.- Elements must be
Comparable(likeString,Integer,LocalDate) or you must pass aComparator. - Real life: a doctor appointment system that shows the earliest free slot, the next slot after a given time, and morning vs afternoon slots.
| Method | Returns | Example with slots [900, 930, 1030, 1100, 1430, 1600] |
|---|---|---|
first() / last() | Smallest / largest | 900 / 1600 |
floor(x) | Greatest element at or below x | floor(1200) = 1100 |
ceiling(x) | Smallest element at or above x | ceiling(1000) = 1030 |
lower(x) / higher(x) | Strictly below / above x | higher(1100) = 1430 |
headSet(x) | Elements below x | headSet(1200) = [900, 930, 1030, 1100] |
tailSet(x) | Elements at or above x | tailSet(1200) = [1430, 1600] |
subSet(a, b) | Elements from a (included) to b (excluded) | subSet(930, 1430) = [930, 1030, 1100] |
pollFirst() / pollLast() | Remove and return smallest / largest | Book the earliest slot |
descendingSet() | Reverse-order view | Latest slots first |
import java.util.List;
import java.util.TreeSet;
public class DoctorSlots {
public static void main(String[] args) {
TreeSet<Integer> freeSlots = new TreeSet<>(List.of(900, 930, 1100, 1430, 1600, 1030));
System.out.println(freeSlots); // [900, 930, 1030, 1100, 1430, 1600]
System.out.println("Earliest: " + freeSlots.first()); // 900
System.out.println("At or after 1000: " + freeSlots.ceiling(1000)); // 1030
System.out.println("At or before 1200: " + freeSlots.floor(1200)); // 1100
System.out.println("Morning: " + freeSlots.headSet(1200)); // [900, 930, 1030, 1100]
System.out.println("Afternoon: " + freeSlots.tailSet(1200)); // [1430, 1600]
int booked = freeSlots.pollFirst(); // book the earliest slot
System.out.println("Booked " + booked + ", left " + freeSlots);
System.out.println("Latest first: " + freeSlots.descendingSet()); // [1600, 1430, 1100, 1030, 930]
}
} Differences between ArrayList and HashSet
| Point | ArrayList | HashSet |
|---|---|---|
| Interface | List | Set |
| Duplicates | Allowed | Not allowed |
| Order | Insertion order | No order |
| Index access | Yes: get(i) | No |
contains | O(n) — scans the list | O(1) average — hashing |
add | Amortized O(1) at end | O(1) average |
| null | Many allowed | One allowed |
| Internal structure | Dynamic array | Hash table (HashMap) |
| Use when | Order and positions matter | Uniqueness and fast lookups matter |
| Real life | Playlist with repeated songs | Set of unique voter IDs |
Advanced — HashSet / TreeSet
How HashSet works internally
- A HashSet wraps a
HashMap. Each element you add becomes a key, and a shared dummy object (PRESENT) is the value. - The map has an array of buckets.
hashCode()decides the bucket; inside a bucket,equals()decides whether the element is already there. - Real life: a post office with pigeonholes by PIN code. To check whether a letter is already there, the clerk looks only in that one pigeonhole, not the whole office.
| Step | What happens in set.add(e) |
|---|---|
| 1 | Call e.hashCode() |
| 2 | Spread the bits: h ^ (h >>> 16) so high bits also matter |
| 3 | Find the bucket: index = hash & (capacity - 1) |
| 4 | If the bucket is empty, store the element — return true |
| 5 | Otherwise compare with each element in the bucket: same hash and equals true means duplicate — return false |
| 6 | No match: add to the bucket (list, or tree if it grows large) |
| 7 | If size exceeds capacity × load factor, double the capacity and rehash |
import java.util.HashSet;
import java.util.Set;
public class BucketDemo {
static int bucketIndex(Object key, int capacity) {
int h = key.hashCode();
h = h ^ (h >>> 16); // HashMap spreads high bits into low bits
return h & (capacity - 1); // same as h % capacity for powers of 2
}
public static void main(String[] args) {
String[] pins = { "500001", "500081", "411001", "600001" };
for (String p : pins) {
System.out.println(p + " hashCode=" + p.hashCode() + " bucket=" + bucketIndex(p, 16));
}
Set<String> set = new HashSet<>();
for (String p : pins) set.add(p);
System.out.println(set.add("500001")); // false: same hash and equals, so a duplicate
}
} Capacity, load factor, and rehashing
| Term | Default | Meaning |
|---|---|---|
| Initial capacity | 16 buckets | Size of the bucket array |
| Load factor | 0.75 | How full the table may get before growing |
| Threshold | 16 × 0.75 = 12 | Adding the 13th element triggers a resize |
| Resize | Capacity doubles (16, 32, 64, ...) | All elements are rehashed into the new array — costly |
| Treeify | More than 8 in one bucket and capacity at least 64 | Bucket becomes a red-black tree (O(log n) worst case) |
| Pre-sizing | HashSet.newHashSet(n) or new HashSet<>((int) (n / 0.75f) + 1) | Avoids repeated rehashing for big sets |
equals and hashCode contract
- Rule 1: if
a.equals(b)is true, thena.hashCode() == b.hashCode()must be true. - Rule 2: equal hash codes do not mean equal objects (collisions are allowed);
equalsmakes the final decision. - Rule 3: use the same fields in both methods, and keep those fields immutable while the object is in a set.
- Real life: a coupon system. If the coupon code DIWALI50 is not recognised as a duplicate, a customer can apply it twice.
| Situation | Result in a HashSet |
|---|---|
| Both overridden correctly | Duplicates detected, O(1) speed |
Only equals overridden | Equal objects land in different buckets — duplicates stored |
Only hashCode overridden | Same bucket, but identity equals — duplicates stored |
Constant hashCode() like return 1 | Correct but every element in one bucket — very slow |
hashCode uses fields not in equals | Equal objects may get different hashes — broken |
Field in hashCode changed after adding | Element lost: contains and remove fail |
import java.util.HashSet;
import java.util.Set;
public class CouponCheck {
static class BadCoupon {
final String code;
BadCoupon(String code) {
this.code = code;
}
@Override
public boolean equals(Object o) {
return o instanceof BadCoupon c && c.code.equals(code);
}
// hashCode NOT overridden: each object gets a different identity hash
}
record Coupon(String code) { } // records generate equals and hashCode
public static void main(String[] args) {
Set<BadCoupon> bad = new HashSet<>();
bad.add(new BadCoupon("DIWALI50"));
bad.add(new BadCoupon("DIWALI50"));
System.out.println("Bad set size: " + bad.size()); // 2: coupon applied twice!
Set<Coupon> good = new HashSet<>();
good.add(new Coupon("DIWALI50"));
good.add(new Coupon("DIWALI50"));
System.out.println("Good set size: " + good.size()); // 1
}
} Mutable elements: the lost element trap
- If you change a field used in
hashCode()after adding the object, its stored bucket no longer matches its new hash. - The set then cannot find it:
containsandremovereturn false, but the object still sits inside, causing memory leaks and wrong counts. - Fix: make such fields
final(immutable objects or records), or remove the object, change it, and add it again.
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class LostElement {
static class Badge {
String id; // mutable: dangerous in a HashSet
Badge(String id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
return o instanceof Badge b && b.id.equals(id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
public static void main(String[] args) {
Set<Badge> insideOffice = new HashSet<>();
Badge badge = new Badge("EMP-101");
insideOffice.add(badge);
badge.id = "EMP-999"; // changed after adding
System.out.println(insideOffice.contains(badge)); // false: wrong bucket
System.out.println(insideOffice.remove(badge)); // false: cannot remove it
System.out.println(insideOffice.size()); // 1: element lost inside
}
} Time complexity of HashSet, LinkedHashSet, and TreeSet
| Operation | HashSet | LinkedHashSet | TreeSet |
|---|---|---|---|
add | O(1) average | O(1) average | O(log n) |
contains | O(1) average | O(1) average | O(log n) |
remove | O(1) average | O(1) average | O(log n) |
| Worst case (many collisions) | O(log n) with tree bins | O(log n) with tree bins | O(log n) |
| Iteration | O(capacity + n) | O(n) | O(n) |
first / last / floor / ceiling | Not available | getFirst / getLast only (Java 21) | O(log n) |
Immutable sets and EnumSet
Set.of(...)(Java 9) creates an immutable set. It rejectsnull, rejects duplicate arguments withIllegalArgumentException, and throws onaddorremove.Set.copyOf(c)makes an immutable snapshot;Collections.unmodifiableSet(s)makes a read-only view.EnumSetis a super-fast, compact set for enum constants, stored internally as bits.- Real life: the fixed metro lines of a city (immutable), and the days a shop is open (EnumSet).
import java.util.EnumSet;
import java.util.Set;
public class ShopTimings {
enum Day { MON, TUE, WED, THU, FRI, SAT, SUN }
public static void main(String[] args) {
Set<String> metroLines = Set.of("Red", "Blue", "Green"); // immutable
// Set.of("Red", "Red"); // IllegalArgumentException
// metroLines.add("Pink"); // UnsupportedOperationException
System.out.println(metroLines.contains("Blue")); // true
EnumSet<Day> open = EnumSet.range(Day.MON, Day.SAT);
EnumSet<Day> closed = EnumSet.complementOf(open);
EnumSet<Day> openWeekend = EnumSet.of(Day.SAT, Day.SUN);
openWeekend.retainAll(open);
System.out.println("Open: " + open); // [MON, TUE, WED, THU, FRI, SAT]
System.out.println("Closed: " + closed); // [SUN]
System.out.println("Open on weekend: " + openWeekend); // [SAT]
}
} Thread-safe sets
HashSetis not thread-safe. Concurrentaddcalls from several threads can lose elements or corrupt the table.
| Option | Ordered? | Use when |
|---|---|---|
Collections.synchronizedSet(new HashSet<>()) | No | Simple, low traffic; lock manually while iterating |
ConcurrentHashMap.newKeySet() | No | Best general-purpose concurrent set |
CopyOnWriteArraySet | Insertion order | Small sets, many reads, rare writes |
ConcurrentSkipListSet | Sorted | Concurrent sorted set (concurrent TreeSet) |
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class LiveVisitors {
public static void main(String[] args) throws InterruptedException {
Set<String> visitors = ConcurrentHashMap.newKeySet(); // thread-safe set
ExecutorService servers = Executors.newFixedThreadPool(4); // 4 web servers
for (int s = 0; s < 4; s++) {
servers.submit(() -> {
for (int i = 0; i < 1000; i++) {
visitors.add("user-" + (i % 500)); // same 500 users on every server
}
});
}
servers.shutdown();
servers.awaitTermination(5, TimeUnit.SECONDS);
System.out.println("Unique visitors: " + visitors.size()); // always 500
}
} Sets with streams
Collectors.toSet()collects unique values,Collectors.toCollection(TreeSet::new)collects them sorted, anddistinct()removes duplicates while keeping order.- Real life: a food delivery app listing the unique cities it delivered to and the sorted list of customers.
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
public class DeliveryReport {
record Order(String customer, String city) { }
public static void main(String[] args) {
List<Order> orders = List.of(
new Order("Ravi", "Hyderabad"),
new Order("Asha", "Pune"),
new Order("Ravi", "Hyderabad"),
new Order("Kiran", "Chennai"),
new Order("Meena", "Pune")
);
Set<String> cities = orders.stream().map(Order::city).collect(Collectors.toSet());
TreeSet<String> customers = orders.stream()
.map(Order::customer)
.collect(Collectors.toCollection(TreeSet::new));
List<String> citiesInOrder = orders.stream().map(Order::city).distinct().toList();
System.out.println(cities.size() + " cities"); // 3 cities
System.out.println(customers); // [Asha, Kiran, Meena, Ravi]
System.out.println(citiesInOrder); // [Hyderabad, Pune, Chennai]
}
} HashSet best practices
| Do | Do not |
|---|---|
Declare as Set<T> | Expose HashSet<T> in method signatures |
Override equals and hashCode together (or use records) | Override only one of them |
| Use immutable fields for hashing | Change a hashed field while the object is in the set |
Use the boolean from add to detect duplicates | Call contains and then add separately |
Use LinkedHashSet or TreeSet when order matters | Rely on HashSet print order |
Pre-size big sets with HashSet.newHashSet(n) | Let a million-element set rehash many times |
Use ConcurrentHashMap.newKeySet() across threads | Share a plain HashSet between writing threads |
Use a HashSet for frequent contains checks | Call list.contains inside big loops |
Tricky Interview Points
Q1) What is a HashSet?
Answer A Set implementation backed by a HashMap that stores unique elements with no guaranteed order and average O(1) add, contains, and remove.
Q2) How does HashSet prevent duplicates?
Answer It uses hashCode to find the bucket and equals to compare with elements already in that bucket. If an equal element exists, add returns false and nothing changes.
Q3) How does HashSet work internally?
Answer It wraps a HashMap. Each element is stored as a key with a shared dummy value called PRESENT. All operations delegate to the map.
Q4) What does add() return for a duplicate?
Answer false. It returns true only when the element was not already present.
Q5) Does HashSet maintain insertion order?
Answer No. Use LinkedHashSet for insertion order or TreeSet for sorted order.
Q6) Can HashSet contain null?
Answer Yes, one null element. TreeSet with natural ordering does not allow null.
Q7) What is the difference between HashSet, LinkedHashSet, and TreeSet?
Answer HashSet has no order and O(1) operations. LinkedHashSet keeps insertion order with O(1) operations. TreeSet keeps elements sorted with O(log n) operations and navigation methods.
Q8) What is the difference between ArrayList and HashSet?
Answer ArrayList allows duplicates, keeps order, and supports index access, but contains is O(n). HashSet rejects duplicates, has no order or index, and contains is O(1) on average.
Q9) Why must we override both equals and hashCode?
Answer Equal objects must have equal hash codes so they land in the same bucket. If only equals is overridden, equal objects go to different buckets and duplicates are stored.
Q10) Can two different objects have the same hashCode?
Answer Yes. That is a collision. equals then decides whether they are the same. Many collisions slow the set down.
Q11) What happens if hashCode always returns the same value?
Answer The set still works correctly, but every element goes into one bucket, so operations degrade from O(1) to O(n) (or O(log n) with tree bins).
Q12) What happens if you modify an object after adding it to a HashSet?
Answer If the change affects hashCode, the object is in the wrong bucket. contains and remove fail, and the element is effectively lost inside the set.
Q13) What are the default capacity and load factor of HashSet?
Answer Capacity 16 and load factor 0.75. The table doubles when the number of elements exceeds capacity times load factor.
Q14) What is rehashing?
Answer When the threshold is crossed, a bigger bucket array (double the size) is created and every element is placed again according to its hash. It is an expensive O(n) step.
Q15) How do you get union, intersection, and difference of two sets?
Answer Copy one set, then use addAll for union, retainAll for intersection, and removeAll for difference.
Q16) How do you remove duplicates from a list while keeping order?
Answer Pass it through a LinkedHashSet: new ArrayList<>(new LinkedHashSet<>(list)).
Q17) Is HashSet thread-safe?
Answer No. Use Collections.synchronizedSet, ConcurrentHashMap.newKeySet(), CopyOnWriteArraySet, or ConcurrentSkipListSet.
Q18) How does TreeSet decide duplicates?
Answer Using compareTo or the Comparator, not equals. If compare returns 0, the element is treated as a duplicate.
Q19) What is the difference between Set.of and new HashSet?
Answer Set.of creates an immutable set that rejects nulls and duplicate arguments. new HashSet creates a mutable set that allows one null.
Q20) Can we get an element by index from a HashSet?
Answer No. Sets have no index. Iterate, check with contains, or copy into a List if you need positions.
Simple Programs
Website visitor analytics: unique, returning, and new users
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class VisitorAnalytics {
public static void main(String[] args) {
List<String> mondayLog = List.of("u1", "u2", "u3", "u2", "u4", "u1");
List<String> tuesdayLog = List.of("u3", "u5", "u1", "u6", "u5");
Set<String> monday = new HashSet<>(mondayLog);
Set<String> tuesday = new HashSet<>(tuesdayLog);
Set<String> returning = new HashSet<>(monday);
returning.retainAll(tuesday); // came both days
Set<String> newOnTuesday = new HashSet<>(tuesday);
newOnTuesday.removeAll(monday); // first visit on Tuesday
Set<String> allUsers = new HashSet<>(monday);
allUsers.addAll(tuesday);
System.out.println("Monday hits: " + mondayLog.size() + ", unique: " + monday.size()); // 6, 4
System.out.println("Tuesday hits: " + tuesdayLog.size() + ", unique: " + tuesday.size()); // 5, 4
System.out.println("Returning users: " + returning.size()); // 2
System.out.println("New on Tuesday: " + newOnTuesday.size()); // 2
System.out.println("Total unique users: " + allUsers.size()); // 6
}
} Detect a duplicate payment transaction
import java.util.HashSet;
import java.util.Set;
public class DuplicateTransaction {
static String firstDuplicate(String[] txnIds) {
Set<String> seen = new HashSet<>();
for (String id : txnIds) {
if (!seen.add(id)) return id; // O(1) check per transaction
}
return null;
}
public static void main(String[] args) {
String[] batch = { "TXN-881", "TXN-882", "TXN-883", "TXN-882", "TXN-884", "TXN-881" };
String dup = firstDuplicate(batch);
System.out.println(dup == null ? "No duplicates" : "Alert: " + dup + " charged twice");
// Alert: TXN-882 charged twice
}
} Job skill matching
import java.util.Set;
import java.util.TreeSet;
public class SkillMatch {
public static void main(String[] args) {
Set<String> required = Set.of("java", "spring", "sql", "git", "docker");
Set<String> candidate = Set.of("java", "python", "sql", "git");
Set<String> matched = new TreeSet<>(required);
matched.retainAll(candidate);
Set<String> missing = new TreeSet<>(required);
missing.removeAll(candidate);
Set<String> bonus = new TreeSet<>(candidate);
bonus.removeAll(required);
int score = matched.size() * 100 / required.size();
System.out.println("Matched: " + matched); // [git, java, sql]
System.out.println("Missing: " + missing); // [docker, spring]
System.out.println("Bonus skills: " + bonus); // [python]
System.out.println("Match score: " + score + "%"); // 60%
}
} Lottery ticket with 6 unique numbers
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
public class Lottery {
public static void main(String[] args) {
Random random = new Random();
Set<Integer> ticket = new TreeSet<>(); // unique + sorted for printing
int draws = 0;
while (ticket.size() < 6) {
ticket.add(1 + random.nextInt(49)); // duplicates are ignored automatically
draws++;
}
System.out.println("Your ticket: " + ticket); // e.g. [4, 11, 23, 30, 38, 47]
System.out.println("Random draws needed: " + draws);
}
} Simple spam filter
import java.util.HashSet;
import java.util.Set;
public class SpamFilter {
private static final Set<String> BLOCKED = Set.of("lottery", "winner", "free", "urgent", "prize");
static boolean isSpam(String message) {
Set<String> hits = new HashSet<>();
for (String word : message.toLowerCase().split("[^a-z]+")) {
if (BLOCKED.contains(word)) hits.add(word); // O(1) lookup per word
}
System.out.println("Blocked words found: " + hits);
return hits.size() >= 2;
}
public static void main(String[] args) {
System.out.println(isSpam("URGENT: You are a WINNER! Claim your FREE prize now")); // true
System.out.println(isSpam("Meeting moved to 3 pm, free snacks in the hall")); // false
}
} Gift card: find two items that use the full amount
import java.util.HashSet;
import java.util.Set;
public class GiftCardPair {
public static void main(String[] args) {
int[] prices = { 450, 1200, 799, 300, 1450, 950 };
int giftCard = 1750;
Set<Integer> seen = new HashSet<>();
for (int price : prices) {
int need = giftCard - price;
if (seen.contains(need)) { // O(1) lookup instead of a nested loop
System.out.println("Buy items costing " + need + " and " + price); // 300 and 1450
return;
}
seen.add(price);
}
System.out.println("No pair matches the gift card exactly");
}
} Unique words in a speech
import java.util.Set;
import java.util.TreeSet;
public class UniqueWords {
public static void main(String[] args) {
String speech = "We learn Java. We practice Java. We build projects with Java and we grow.";
Set<String> words = new TreeSet<>(); // unique + alphabetical
for (String w : speech.toLowerCase().split("[^a-z]+")) {
if (!w.isEmpty()) words.add(w);
}
System.out.println("Total words: " + speech.split("[^A-Za-z]+").length); // 14
System.out.println("Unique words: " + words.size()); // 9
System.out.println(words);
// [and, build, grow, java, learn, practice, projects, we, with]
}
} Problem Solving Tricks
- Need uniqueness? Think Set. Need fast "have I seen this?" checks? Think HashSet.
- Use
if (!set.add(x))to detect duplicates in one step. - HashSet = no order, LinkedHashSet = insertion order, TreeSet = sorted.
- Always override
equalsandhashCodetogether, using the same fields — or use a record. - Never change a field used in
hashCodewhile the object is inside a set. - Copy before set operations:
new HashSet<>(a)thenaddAll,retainAll, orremoveAll. - Deduplicate a list and keep order:
new ArrayList<>(new LinkedHashSet<>(list)). - Replace
list.containsinside loops with a HashSet lookup to turn O(n²) into O(n). Set.ofis immutable and rejects nulls and duplicate arguments.- For enum values, use
EnumSet; for threads, useConcurrentHashMap.newKeySet().
Practice Programs List
- Simulate a polling booth that rejects duplicate voter IDs using the result of
add. - Count unique visitors from a list of 20 visitor IDs.
- Find students who are in both the cricket and football clubs, and in exactly one club.
- Remove duplicate emails from a signup list while keeping first-signup order.
- Create a
Vehicleclass and show duplicates appearing withoutequalsandhashCode, then fix it. - Rewrite the
Vehicleclass as a record and confirm duplicates are detected. - Print the same names from a HashSet, LinkedHashSet, and TreeSet and explain the order.
- Build a doctor slot system with TreeSet using
first,ceiling,floor, andpollFirst. - Check whether a candidate has all required skills using
containsAll. - Find the first repeated character in a string using a HashSet.
- Check whether a sentence is a pangram (contains every letter a to z) using a Set.
- Generate 6 unique lottery numbers between 1 and 49.
- Show the lost element problem by changing a hashed field after adding to a set.
- Count unique visitors from 4 threads safely with
ConcurrentHashMap.newKeySet().