Skip to content

Java TreeSet ‚Äč

It is a special type of collection in Java that stores elements in a sorted order. It's like having a neatly arranged shelf where items are automatically sorted as you add them, making it easy to find what you need without any extra effort.

java
import java.util.TreeSet;

public class TreeSetExample {
    public static void main(String[] args) {
        TreeSet<String> treeSet = new TreeSet<>();

        // Adding elements to the TreeSet
        treeSet.add("banana");
        treeSet.add("apple");
        treeSet.add("orange");
        treeSet.add("grape");
        treeSet.add("kiwi");

        // Printing the TreeSet
        System.out.println("Fruit TreeSet: " + treeSet);
    }
}

In our example, we've created a TreeSet to store fruits. As we add fruits to the TreeSet, notice how they automatically get sorted in alphabetical order. It's like having a magic spell that organizes your collection effortlessly!

But wait, there's more to TreeSet than just sorting. It also offers a bunch of other handy features, like:

  • Efficient retrieval: TreeSet uses a balanced binary search tree under the hood, which allows for fast retrieval of elements.
  • Automatic sorting: As we've seen, TreeSet automatically sorts its elements, saving you the trouble of sorting them manually.
  • No duplicates: TreeSet automatically eliminates duplicate elements, ensuring that each element in the set is unique.

Now, let's spice things up with a practical example:

java
import java.util.TreeSet;

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

        // Adding elements to the TreeSet
        treeSet.add(5);
        treeSet.add(2);
        treeSet.add(8);
        treeSet.add(3);
        treeSet.add(5); // Duplicate element

        // Printing the TreeSet
        System.out.println("Number TreeSet: " + treeSet);

        // Getting the smallest and largest elements
        System.out.println("Smallest element: " + treeSet.first());
        System.out.println("Largest element: " + treeSet.last());
    }
}

In this example, we've created a TreeSet to store numbers. Notice how TreeSet automatically eliminates the duplicate element "5" and sorts the remaining elements. We can also easily retrieve the smallest and largest elements from the TreeSet with just a couple of method calls.

Waytojava is designed to make learning easier. We simplify examples for better understanding. We regularly check tutorials, references, and examples to correct errors, but it's important to remember that humans can make mistakes.