HashSet & TreeSet
HashSet — Fast, Unordered
HashSet is backed by a hash table (internally, a HashMap whose values are all a shared dummy object). Adding, removing, and checking membership are all O(1) on average, because the element's hash code determines almost directly where it lives in the underlying table — no scanning required.
HashSet basics
import java.util.HashSet;
import java.util.Set;
Set<String> cities = new HashSet<>();
cities.add("Tokyo");
cities.add("Cairo");
cities.add("Lima");
System.out.println(cities.contains("Cairo")); // O(1) average
System.out.println(cities);true [Cairo, Lima, Tokyo]
TreeSet — Sorted, Slower
TreeSet keeps elements sorted automatically
import java.util.Set; import java.util.TreeSet; Set<Integer> scores = new TreeSet<>(); scores.add(42); scores.add(7); scores.add(15); scores.add(99); System.out.println(scores); // always sorted ascending
[7, 15, 42, 99]
TreeSet with a custom Comparator
import java.util.Comparator;
import java.util.TreeSet;
TreeSet<String> byLength =
new TreeSet<>(Comparator.comparingInt(String::length));
byLength.add("kiwi");
byLength.add("fig");
byLength.add("watermelon");
System.out.println(byLength);[fig, kiwi, watermelon]
LinkedHashSet — The Middle Ground
Comparison
Implementation | Backing structure | Ordering | Performance | Best for |
HashSet | Hash table | None — unpredictable | O(1) average | Fastest general-purpose set when order doesn't matter |
LinkedHashSet | Hash table + linked list | Insertion order | O(1) average | Predictable iteration without the cost of sorting |
TreeSet | Red-black tree | Sorted order | O(log n) | When you need elements sorted, or range queries |
HashSet: fastest, no ordering guarantee whatsoever
TreeSet: sorted order, O(log n) operations, supports NavigableSet methods
LinkedHashSet: HashSet speed with predictable insertion-order iteration