Skip to main content

Lesson 3 of 10

Set - HashSet, LinkedHashSet, TreeSet

Set stores unique elements - duplicates are silently ignored. The three main implementations differ in ordering: HashSet (no order), LinkedHashSet (insertion order), TreeSet (sorted order). The choice of Set determines your ordering guarantees and performance.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Set Implementations in Practice

Set Implementations in Practice
import java.util.*;

public class SetDemo {
    public static void main(String[] args) {
        // HashSet - no order, O(1) average for add/contains/remove
        Set<String> genres = new HashSet<>();
        genres.add("Fiction");
        genres.add("Science");
        genres.add("Fiction");   // duplicate - silently ignored
        genres.add("Biography");
        System.out.println(genres.size());       // 3 (not 4)
        System.out.println(genres.contains("Science"));  // true

        // LinkedHashSet - preserves insertion order
        Set<String> ordered = new LinkedHashSet<>();
        ordered.add("Java");
        ordered.add("Python");
        ordered.add("Go");
        ordered.add("Java");  // duplicate ignored, order preserved
        System.out.println(ordered);  // [Java, Python, Go]

        // TreeSet - elements sorted (natural order or Comparator)
        Set<String> sorted = new TreeSet<>();
        sorted.addAll(List.of("Banana", "Apple", "Cherry", "Date"));
        System.out.println(sorted);          // [Apple, Banana, Cherry, Date]
        System.out.println(((TreeSet<String>) sorted).first()); // Apple
        System.out.println(((TreeSet<String>) sorted).last());  // Date

        // TreeSet with custom Comparator (sort by string length, then alphabetically)
        Set<String> byLength = new TreeSet<>(
            Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder())
        );
        byLength.addAll(List.of("Java", "Go", "Python", "Rust", "C"));
        System.out.println(byLength);  // [C, Go, Java, Rust, Python]

        // Set operations
        Set<String> setA = new HashSet<>(Set.of("a", "b", "c", "d"));
        Set<String> setB = new HashSet<>(Set.of("c", "d", "e", "f"));

        Set<String> union = new HashSet<>(setA);
        union.addAll(setB);                    // {a, b, c, d, e, f}

        Set<String> intersection = new HashSet<>(setA);
        intersection.retainAll(setB);          // {c, d}

        Set<String> difference = new HashSet<>(setA);
        difference.removeAll(setB);            // {a, b}

        System.out.println("Union: " + union);
        System.out.println("Intersection: " + intersection);
        System.out.println("Difference: " + difference);
    }
}

Quick Quiz

Tip

Tip

Practice Set HashSet LinkedHashSet TreeSet in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Set - HashSet, LinkedHashSet, TreeSet

Practice Task

Note

Practice Task - (1) Write a working example of Set HashSet LinkedHashSet TreeSet from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Set HashSet LinkedHashSet TreeSet is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.

Topics in This Module

0/10 done