Sets: HashSet, LinkedHashSet, TreeSet
Store unique values and pick the set whose ordering guarantee you actually need.
Open this lesson in the learning hubKey points
- A
Setholds each value once.addreturnsfalseif it was already there — a free duplicate check. HashSetis the fastest. Its iteration order is not guaranteed — never rely on what you see printed.LinkedHashSetcosts a little more and remembers insertion order. Use it when output order matters.TreeSetkeeps elements sorted and addsfirst,ceiling,headSet,subSet.addAllis union,retainAllis intersection,removeAllis difference.
Example
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> input = List.of("pear", "apple", "pear", "fig", "apple");
System.out.println("HashSet : " + new HashSet<>(input));
System.out.println("LinkedHashSet : " + new LinkedHashSet<>(input));
System.out.println("TreeSet : " + new TreeSet<>(input));
Set<String> seen = new HashSet<>();
System.out.println("first add fig: " + seen.add("fig"));
System.out.println("second add fig: " + seen.add("fig"));
TreeSet<String> sorted = new TreeSet<>(input);
System.out.println("first / last : " + sorted.first() + " / " + sorted.last());
System.out.println("ceiling(b) : " + sorted.ceiling("b"));
System.out.println("headSet(fig) : " + sorted.headSet("fig"));
Set<String> a = new LinkedHashSet<>(List.of("x", "y", "z"));
Set<String> b = Set.of("y", "z", "w");
Set<String> union = new LinkedHashSet<>(a);
union.addAll(b);
Set<String> shared = new LinkedHashSet<>(a);
shared.retainAll(b);
System.out.println("union size : " + union.size());
System.out.println("intersection : " + shared);
}
}
HashSet for speed, LinkedHashSet for predictable order, TreeSet for sorted queries.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Collections course, and every lesson in it is listed on the Collections contents page.