Core Java

TreeSet In Java

Introduction:

TreeSet in Java is a sorted set of items stored in a tree-like structure. It implements the NavigableSet interface and extends AbstractSet class.

Some of the properties of TreeSet includes:

  1. Unique collection of items
  2. Elements stored in a sorted order
  3. Faster access and retrieval of items

The default ordering in a TreeSet is in ascending order unless specified otherwise. Another key point to remember is that a TreeSet cannot store a null value. Any attempt to do so will result in a NullPointerException.

The internal Java implementation of a TreeSet is that of a self-balancing tree like Red-Black Tree, so it takes only O(logn) time to add, remove or search an item.

Moreover, it takes only O(n) time to traverse the entire TreeSet.

Instantiating a TreeSet:

We can use one of the many constructors available in java.util.TreeSet to initialize a TreeSet in Java:

TreeSet() //creates an empty TreeSet with default sorting order(asc)
TreeSet(Collection c) //creates TreeSet and initializes it with elements in c
TreeSet(Comparator comp) //creates TreeSet which uses comp to sort elements
TreeSet(SortedSet ss) // creates a TreeSet with elements of ss

Methods In TreeSet:

Let’s explore the commonly used methods available in the TreeSet class:

1. void add(Object obj) : Adds an item to the TreeSet, if not already present. Duplicate entries will simply be ignored.

2. boolean addAll(Collection c): It adds all the unique elements of Collection c to the TreeSet. Duplicate entries are simply ignored.

3. boolean contains(Object obj): It returns true if obj is present in our Set, false otherwise.

4. boolean remove(Object c): It removes an object obj from the TreeSet if present.

5. boolean isEmpty(): Returns true if the Set is empty, false otherwise.

6. void clear(): Resets our TreeSet by removing all elements from it.

7. int size(): Returns the size of our TreeSet.

8. Object clone(): Returns a shallow copy of our TreeSet.

9. Iterator iterator(): Returns an Iterator to help us iterate over our TreeSet.

10. Object first(): If TreeSet is not empty, it returns the first element in our TreeSet otherwise throws a NoSuchElementException.

11. Object last(): If TreeSet is not empty, it returns the last element in the TreeSet otherwise throws a NoSuchElementException.

12. SortedSet headSet(Object endElement): It returns all elements in the TreeSet with a value less than the specified element.

13. SortedSet tailSet(Object startElement): It returns all elements in a TreeSet greater than or equal to the specified element.

14. SortedSet subSet(Object startElement, Object endElement): Returns all elements greater than or equal to startElement and less than endElement.

Example Usage:

Let’s try to implement what we have learned:

Set<Integer> treeSet = new TreeSet<Integer>();
treeSet.add(5);
treeSet.add(1);
treeSet.add(7);
treeSet.add(4);

int firstElement = treeSet.first(); // returns 1
int lastElement = treeSet.last(); // returns 7

//Iterating a TreeSet In Asc Order
Iterator<Integer> itr = treeSet.iterator();
while(itr.hasNext()) {
    System.out.println(itr.next());
} 

//Iterating a TreeSet In Desc Order
itr = treeSet.descendingIterator();
while(itr.hasNext()) {
    System.out.println(itr.next());
} 

treeSet.remove(1); //removes element 1

int treeSetSize = treeSet.size(); //returns 3

Conclusion:

In this tutorial, we learned about TreeSet in Java. We explored its library and we now know how and when to use it. The mantra is to use it whenever we want to maintain a sorted set of items.

TreeSet is a very efficient data structure with only O(log n) retrieval/item addition or removal time. For iteration, it takes about O(n) time.

If we are storing and working with custom objects, we can pass in our own Comparator implementation to the TreeSet constructor.

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *