ProLesson 7.3Intermediate2 min readUpdated 30 October 2026
Set: HashSet, LinkedHashSet and TreeSet
Keep only unique items, choose between hash, insertion-ordered and sorted sets, and do set maths like union and intersection.
A Set stores unique elements: adding something that's already there does nothing. Perfect for tags, visited pages, unique emails, or "have I seen this before?" checks.
01Three implementations
SetTypes.java
import java.util.*;
public class SetTypes {
public static void main(String[] args) {
List<String> visits = List.of("home", "cart", "home", "pay", "cart");
Set<String> linked = new LinkedHashSet<>(visits);
Set<String> sorted = new TreeSet<>(visits);
Set<String> hashed = new HashSet<>(visits);
System.out.println(linked); // first-seen order
System.out.println(sorted); // alphabetical
System.out.println(hashed.size()); // order not guaranteed, so we print the size
System.out.println(hashed.contains("pay"));
System.out.println(linked.add("home")); // false: already present
}
}[home, cart, pay] [cart, home, pay] 3 true false
| HashSet | LinkedHashSet | TreeSet | |
|---|---|---|---|
| Order | None you can rely on | Insertion order | Sorted |
add / contains | O(1) on average | O(1) on average | O(log n) |
| Backed by | HashMap | LinkedHashMap | A red-black tree (TreeMap) |
null allowed | One | One | No (with natural ordering) |
Loading the rest of the lesson…