Sets: HashSet, LinkedHashSet, TreeSet

Collections · lesson 4 of 42 · 3 min read

Store unique values and pick the set whose ordering guarantee you actually need.

Open this lesson in the learning hub

Key points

  • A Set holds each value once. add returns false if it was already there — a free duplicate check.
  • HashSet is the fastest. Its iteration order is not guaranteed — never rely on what you see printed.
  • LinkedHashSet costs a little more and remembers insertion order. Use it when output order matters.
  • TreeSet keeps elements sorted and adds first, ceiling, headSet, subSet.
  • addAll is union, retainAll is intersection, removeAll is 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.