Set membership and ordering
What you will learn
A Set is useful when an item should appear only once. Choose a set implementation according to how membership is decided and whether you need a predictable iteration order.
- Deduplicate values with HashSet, LinkedHashSet or TreeSet.
- Explain how comparison equality affects TreeSet membership.
- Choose a set with appropriate null and ordering contracts.
Use a fresh directory per example. Save as Main.java, compile with javac --release 21 Main.java, then run java Main. Only JDK standard-library dependencies are needed.
Deduplicate visits and preserve arrival order
import java.util.*;public class Main {
public static void main(String[] args) { List<String> visits = List.of("B", "A", "B", "C"); Set<String> unique = new HashSet<>(visits); Set<String> arrival = new LinkedHashSet<>(visits); Set<String> sorted = new TreeSet<>(visits); System.out.println(unique.size()); System.out.println(unique.contains("A")); System.out.println(arrival); System.out.println(sorted); }}Expected output:
3true[B, A, C][A, B, C]Only the ordered implementations are printed as sequences. Repeated B does not create another member.
Rules and mental model
Set<E> extends Collection<E> but provides no universal indexed access or iteration order. HashSet uses hashing and equality and allows a null element; membership operations are normally constant-time given well-distributed hashes. Its iteration order is unspecified. LinkedHashSet retains ordinary insertion order and supports sequenced operations in Java 21. Adding an existing element with add does not move it; addFirst/addLast may reposition it. TreeSet orders elements by their natural order or a supplied comparator, with logarithmic basic membership operations. Comparison zero is treated as an existing element; to meet the general Set equality contract, the ordering must agree with equals. Natural-order TreeSet rejects null; a comparator may explicitly support null. Set.of rejects null and repeated arguments, while Set.copyOf accepts duplicate elements from a source collection and rejects null; both produce unmodifiable sets with unspecified iteration order. Do not mutate fields that determine equality, hashing or comparison while a value is stored.
Recognize a comparison tie
import java.util.*;public class Main { static final class LengthOrder implements Comparator<String> { public int compare(String a, String b) { return Integer.compare(a.length(), b.length()); } } public static void main(String[] args) { Set<String> byLength = new TreeSet<>(new LengthOrder()); System.out.println(byLength.add("cat")); System.out.println(byLength.add("dog")); System.out.println(byLength.contains("owl")); System.out.println(byLength); }}Expected output:
truefalsetrue[cat]All three names have length 3. This comparator deliberately disagrees with String.equals, so use it only to demonstrate the hazard, not as a general set of names.
Reorder an encounter-ordered set
import java.util.*;public class Main {
public static void main(String[] args) { SequencedSet<String> route = new LinkedHashSet<>(List.of("B", "A", "C")); System.out.println(route.add("A")); route.addFirst("C"); System.out.println(route); System.out.println(route.reversed()); }}Expected output:
false[C, B, A][A, B, C]Ordinary add leaves an existing member in place. Java 21 addFirst moves C to the front; reversed exposes opposite encounter order.
Common mistakes
Do not print a HashSet or Set.of and treat the observed order as a guarantee. For deterministic output, choose LinkedHashSet for encounter order or TreeSet for sorted order. A set is not a list with automatically removed duplicates at each index.
Practice
Given visits [N, S, N, E], preserve first-visit order in one set and alphabetic order in another. Print both sets and whether adding N to the first set changed membership.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Set membership and ordering — knowledge check
Apply the chapter contracts and reason about Java 21-compatible examples.
Which set preserves ordinary insertion order?
What does HashSet.add return for an existing equal value?
A TreeSet comparator returns zero for two different names. What happens when the second is added?
What does Set.of("A", "A") do?
What does addFirst("B") do to Java 21 LinkedHashSet [A, B, C]?