Skip to content
Veltoryx Technologies
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
    }
}
Expected output
[home, cart, pay]
[cart, home, pay]
3
true
false
HashSetLinkedHashSetTreeSet
OrderNone you can rely onInsertion orderSorted
add / containsO(1) on averageO(1) on averageO(log n)
Backed byHashMapLinkedHashMapA red-black tree (TreeMap)
null allowedOneOneNo (with natural ordering)

Loading the rest of the lesson…