Java TreeSet

Sorted collection that maintains unique elements automatically

🌳 What is TreeSet?

TreeSet is a sorted collection in Java that automatically arranges elements in ascending order and prevents duplicates. It's perfect when you need unique, sorted data storage.


// Simple TreeSet example
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(5);
numbers.add(2);
numbers.add(8);
System.out.println(numbers); // [2, 5, 8]
                                    

TreeSet Key Features

🔢

Auto-Sorting

Elements are automatically sorted

TreeSet<String> names = new TreeSet<>();
names.add("Charlie");
names.add("Alice");
names.add("Bob");
// Output: [Alice, Bob, Charlie]
🚫

No Duplicates

Automatically removes duplicate values

TreeSet<Integer> set = new TreeSet<>();
set.add(1);
set.add(1); // Duplicate ignored
set.add(2);
// Output: [1, 2]
âš¡

Fast Operations

Efficient search, insert, and delete

TreeSet<Integer> set = new TreeSet<>();
set.add(10);
boolean exists = set.contains(10); // true
set.remove(10);
// All operations are O(log n)
🎯

Range Operations

Get subsets within ranges

TreeSet<Integer> set = new TreeSet<>();
set.addAll(Arrays.asList(1,3,5,7,9));
SortedSet<Integer> subset = set.subSet(3, 8);
// Output: [3, 5, 7]

🔹 Creating and Using TreeSet

Here's how to create and work with TreeSet:

import java.util.*;

public class TreeSetExample {
    public static void main(String[] args) {
        // Create a TreeSet
        TreeSet<String> fruits = new TreeSet<>();
        
        // Add elements
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        fruits.add("Apple"); // Duplicate - will be ignored
        
        // Display sorted elements
        System.out.println("Fruits: " + fruits);
        // Output: [Apple, Banana, Cherry]
        
        // Check if element exists
        if (fruits.contains("Banana")) {
            System.out.println("Banana is in the set");
        }
        
        // Remove element
        fruits.remove("Banana");
        System.out.println("After removal: " + fruits);
    }
}

Output:

Fruits: [Apple, Banana, Cherry]

Banana is in the set

After removal: [Apple, Cherry]

🔹 TreeSet with Custom Objects

Use TreeSet with custom objects by implementing Comparable:

class Student implements Comparable<Student> {
    String name;
    int age;
    
    Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    @Override
    public int compareTo(Student other) {
        return this.age - other.age; // Sort by age
    }
    
    @Override
    public String toString() {
        return name + "(" + age + ")";
    }
}

// Usage
TreeSet<Student> students = new TreeSet<>();
students.add(new Student("Alice", 20));
students.add(new Student("Bob", 18));
students.add(new Student("Charlie", 22));

System.out.println(students);
// Output: [Bob(18), Alice(20), Charlie(22)]

Output:

[Bob(18), Alice(20), Charlie(22)]

🔹 Common TreeSet Methods

Essential methods for working with TreeSet:

TreeSet<Integer> numbers = new TreeSet<>();
numbers.addAll(Arrays.asList(5, 2, 8, 1, 9, 3));

// Basic operations
System.out.println("Size: " + numbers.size()); // 6
System.out.println("First: " + numbers.first()); // 1
System.out.println("Last: " + numbers.last()); // 9

// Range operations
System.out.println("Lower than 5: " + numbers.headSet(5)); // [1, 2, 3]
System.out.println("5 and higher: " + numbers.tailSet(5)); // [5, 8, 9]
System.out.println("Between 2 and 8: " + numbers.subSet(2, 8)); // [2, 3, 5]

// Navigation
System.out.println("Higher than 5: " + numbers.higher(5)); // 8
System.out.println("Lower than 5: " + numbers.lower(5)); // 3

Output:

Size: 6

First: 1

Last: 9

Lower than 5: [1, 2, 3]

5 and higher: [5, 8, 9]

Between 2 and 8: [2, 3, 5]

Higher than 5: 8

Lower than 5: 3

🧠 Test Your Knowledge

What happens when you add duplicate elements to a TreeSet?