Sets

A set is a collection with no duplicates. It answers "is this item in the collection?" very quickly, which makes sets ideal for tracking visited pages, unique tags, or which users have voted. Java offers three main implementations with different ordering guarantees.

HashSet

JAVA
import java.util.HashSet;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        Set<String> tags = new HashSet<>();
        System.out.println(tags.add("java"));
        System.out.println(tags.add("sql"));
        System.out.println(tags.add("java"));
        System.out.println(tags.size());
        System.out.println(tags.contains("sql"));
        tags.remove("sql");
        System.out.println(tags);
    }
}
Output
true
true
false
2
true
[java]

add returns false when the element was already present. HashSet makes no promise about iteration order — don't rely on the order it prints in.

Removing duplicates

JAVA
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> visits = List.of("home", "shop", "home", "cart", "shop", "checkout");
        List<String> unique = new ArrayList<>(new LinkedHashSet<>(visits));
        System.out.println(unique);
    }
}
Output
[home, shop, cart, checkout]

LinkedHashSet remembers insertion order, so this removes duplicates while keeping the first occurrence of each.

TreeSet: sorted

JAVA
import java.util.TreeSet;

public class Main {
    public static void main(String[] args) {
        TreeSet<Integer> scores = new TreeSet<>(java.util.List.of(72, 95, 61, 88, 95));
        System.out.println(scores);
        System.out.println(scores.first() + " " + scores.last());
        System.out.println(scores.ceiling(80));
        System.out.println(scores.headSet(80));
        System.out.println(scores.descendingSet());
    }
}
Output
[61, 72, 88, 95]
61 95
88
[61, 72]
[95, 88, 72, 61]

TreeSet keeps elements sorted and offers range queries: the smallest element at least 80 (ceiling), everything below 80 (headSet), and so on.

Choosing an implementation

ClassOrderSpeed of add/contains
HashSetNoneFastest (constant time)
LinkedHashSetInsertion orderNearly as fast
TreeSetSortedSlower (logarithmic)
Set.of(…)None (unmodifiable)Fast

Hash sets rely on correct equals and hashCode (lesson 35); tree sets rely on compareTo or a Comparator.

Set operations

JAVA
import java.util.Set;
import java.util.TreeSet;

public class Main {
    public static void main(String[] args) {
        Set<String> anaLikes = Set.of("jazz", "film", "hiking", "chess");
        Set<String> benLikes = Set.of("chess", "football", "jazz");

        Set<String> both = new TreeSet<>(anaLikes);
        both.retainAll(benLikes);

        Set<String> either = new TreeSet<>(anaLikes);
        either.addAll(benLikes);

        Set<String> onlyAna = new TreeSet<>(anaLikes);
        onlyAna.removeAll(benLikes);

        System.out.println("Both: " + both);
        System.out.println("Either: " + either);
        System.out.println("Only Ana: " + onlyAna);
    }
}
Output
Both: [chess, jazz]
Either: [chess, film, football, hiking, jazz]
Only Ana: [film, hiking]

retainAll (intersection), addAll (union) and removeAll (difference) modify the set they're called on, so copy first.

Try it yourself

Find the first repeated word in a sentence.

Try it yourself · Main.java
Edit the code, copy it into Main.java and run java Main.java (Java 25+). How to set up Java
Output
First repeat: the
4 distinct words before stopping