Java TreeSet
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

Java TreeSet

Jeevadharshan

Java TreeSet 

The TreeSet class is a part of the Java Collections Framework and is used to store a collection of unique elements in sorted order. It belongs to the java.util package and implements the Set interface. 

Unlike HashSet, which stores elements without any guaranteed order, TreeSet automatically sorts its elements using their natural ordering (alphabetical for strings or ascending for numbers). 

Because TreeSet maintains a sorted structure internally, it is commonly used in applications where ordered and unique data is required. 

Key Features of TreeSet 

TreeSet provides several useful characteristics that make it different from other Set implementations. 

Automatically Sorted Elements 

Elements in a TreeSet are always stored in sorted order. 

No Duplicate Values 

Just like other Set implementations, duplicate elements are not allowed. 

No Index-Based Access 

TreeSet does not support index-based operations like a List. 

Slower Than HashSet 

Because TreeSet maintains sorted order, its operations are slightly slower than HashSet, which focuses purely on performance. 

Creating a TreeSet in Java 

To use TreeSet, you must first import the class from the java.util package, then create an object of the class. 

Example: Creating a TreeSet 
 
import java.util.TreeSet; 
 
public class DepartmentSetExample { 
 
    public static void main(String[] args) { 
 
        TreeSet<String> departments = new TreeSet<>(); 
 
        departments.add("Mechanical"); 
        departments.add("Computer Science"); 
        departments.add("Civil"); 
        departments.add("Electronics"); 
 
        System.out.println("Departments: " + departments); 
    } 
}  

Output  

The elements will automatically appear in sorted alphabetical order. 

Adding Elements to a TreeSet 

You can add elements using the add() method. If a duplicate value is added, it will be ignored. 
 
Example: Adding Book Titles 
 
import java.util.TreeSet; 
 
public class BookCollectionExample { 
 
    public static void main(String[] args) { 
 
        TreeSet<String> books = new TreeSet<>(); 
 
        books.add("Data Structures"); 
        books.add("Operating Systems"); 
        books.add("Computer Networks"); 
        books.add("Data Structures"); // Duplicate element 
 
        System.out.println("Book Collection: " + books); 
    } 
 
Important Note 

Even though "Data Structures" is added twice, it appears only once because TreeSet stores 
unique elements only. 

Checking if an Element Exists 

The contains() method is used to check whether an element exists in the TreeSet. 

Example 

if(books.contains("Operating Systems")) { 
   System.out.println("The book is available in the collection."); 

This method is useful for fast membership checks. 

Removing Elements from a TreeSet 

To delete a specific element from a TreeSet, use the remove() method. 

Example 

books.remove("Computer Networks"); 

If you want to remove all elements, use the clear() method. 

books.clear(); 

Finding the Size of a TreeSet 

The size() method returns the total number of unique elements in the TreeSet. 

Example 

System.out.println("Total Books: " + books.size()); 

Duplicate values are not counted. 

Iterating Through a TreeSet 

You can loop through the elements of a TreeSet using a for-each loop. 
 
Example: Displaying Sorted Subjects 
 
import java.util.TreeSet; 
 
public class SubjectIteratorExample { 
 
    public static void main(String[] args) { 
 
        TreeSet<String> subjects = new TreeSet<>(); 
 
        subjects.add("Mathematics"); 
        subjects.add("Physics"); 
        subjects.add("Chemistry"); 
        subjects.add("Biology"); 
 
        for(String subject : subjects) { 
            System.out.println(subject); 
        } 
    } 
 
Since TreeSet maintains order, the elements will be printed alphabetically. 

Using TreeSet with Numbers 

TreeSet can also store numeric values. Numbers are automatically sorted from smallest to largest. 
 
Example: Sorting Scores 
 
import java.util.TreeSet; 
 
public class ScoreSetExample { 
 
    public static void main(String[] args) { 
 
        TreeSet<Integer> scores = new TreeSet<>(); 
 
        scores.add(85); 
        scores.add(70); 
        scores.add(95); 
        scores.add(60); 
 
        for(Integer score : scores) { 
 
            System.out.println(score); 
        } 
    } 
}  

Output Order 

60 
70 
85 
95

HashSet vs TreeSet 

 Both HashSet and TreeSet implement the Set interface, but they behave differently. 

Table

Feature HashSet  TreeSet 
Ordering No guaranteed order Automatically sorted 
Duplicate Elements Not allowed Not allowed 
Performance  Faster  Slightly slower due to sorting 
Use Case     Fast data storage  Sorted data storage 

Tip: 
Use HashSet when performance is more important than order, and use TreeSet when you need sorted elements.  

Using the var Keyword (Java 10+) 

Starting from Java 10, you can declare variables using the var keyword, which allows the compiler to infer the variable type automatically. 
 
Example 
 
var skills = new TreeSet<String>(); 
 
skills.add("Java"); 
skills.add("Python"); 
skills.add("Machine Learning"); 
 
 
Although var makes the code shorter, many developers prefer using explicit types for readability. 

Using the Set Interface with TreeSet 

In professional Java development, it is common to declare variables using the Set interface instead of the specific implementation class. 
 
Example 
 
import java.util.Set; 
import java.util.TreeSet; 
 
public class SkillSetExample { 
 
    public static void main(String[] args) { 
 
        Set<String> skills = new TreeSet<>(); 
 
        skills.add("Java"); 
        skills.add("SQL"); 
        skills.add("Spring"); 
 
        System.out.println(skills); 
    } 
 
This approach makes the program more flexible, allowing developers to change the underlying implementation without modifying other parts of the code.
Our website uses cookies to enhance your experience. Learn More
Accept !