Java TreeSet

h‮t‬tps://www.theitroad.com

In Java, TreeSet is a class that implements the NavigableSet interface, which extends the SortedSet interface to provide a collection that is sorted in ascending order by default. Like other Set implementations, TreeSet does not allow duplicate elements, and its elements are stored in a binary search tree. As a result, TreeSet has faster search and retrieval times than HashSet or LinkedHashSet, but slower insertion and deletion times.

Here's an example of how to use a TreeSet in Java:

import java.util.TreeSet;

public class TreeSetExample {
    public static void main(String[] args) {
        // Create a new TreeSet
        TreeSet<Integer> set = new TreeSet<>();

        // Add elements to the set
        set.add(3);
        set.add(1);
        set.add(2);

        // Print the set
        System.out.println(set);

        // Iterate over the set
        for (Integer i : set) {
            System.out.print(i + " ");
        }
    }
}

Output:

[1, 2, 3]
1 2 3

In the example above, we have created a TreeSet of integers, and added three elements to it. The elements are automatically sorted in ascending order when added to the set. We have printed the set using System.out.println(), which shows the elements in the sorted order. We have also iterated over the set using a for-each loop, which prints the elements in the same order as they were added to the set.

TreeSet also provides all the methods provided by NavigableSet, including ceiling(), floor(), higher(), and lower(), which we discussed in the previous answer on NavigableSet. Additionally, TreeSet also provides methods for retrieving the first and last elements of the set, and for removing the first and last elements of the set, using the first(), last(), pollFirst(), and pollLast() methods.