Java Intermediate

0% completed

Previous
Next
Basics of TreeSet Class

The TreeSet class in Java is a concrete implementation of the NavigableSet, which implements the SortedSet` interface that stores elements in a sorted order. By default, it arranges its elements in their natural order (for example, alphabetical order for strings or ascending order for numbers).

Image

A key advantage of using TreeSet is that it automatically sorts the elements as they are added, while also ensuring that all elements are unique.

  • Sorted Order: Automatically sorts elements in natural order.
  • Unique Elements: Does not allow duplicate values.
  • Efficient Operations: Offers efficient performance (O(log n)) for add, remove, and search operations due to its underlying Red-Black tree structure.

Syntax for Creating a TreeSet

TreeSet<Type> treeSet = new TreeSet<Type>();
  • Explanation:
    • TreeSet<Type> declares a TreeSet that will store objects of the specified Type.
    • The default constructor creates an empty TreeSet that automatically orders its elements using their natural ordering.

Example: Basic Operations with TreeSet (Natural Order)

In this example, we create a TreeSet of strings to store fruit names. As elements are added, they are automatically sorted in alphabetical order. We then print the TreeSet to see the sorted order.

Java
Java

. . . .

Example Explanation :

  • TreeSet Creation:
    • A TreeSet<String> named fruits is created.
  • Adding Elements:
    • Elements are added using the add() method.
    • The order of insertion does not affect the final order because TreeSet automatically sorts the elements.
  • Automatic Sorting:
    • The TreeSet sorts the fruit names in natural (alphabetical) order (e.g., "Apple", "Banana", "Cherry", "Date").
  • Outcome:
    • When printed, the TreeSet displays the elements in sorted order, regardless of the order in which they were added.

The TreeSet class is an ideal choice when you need a collection of unique elements that are automatically maintained in a sorted order. Understanding the basics of TreeSet lays the groundwork for more advanced operations, such as using custom comparators to define alternate sorting orders, which will be covered in subsequent lessons.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next