Java Collections

TreeSet Class in Collection

public class TreeSet<E>
extends AbstractSet<E>
implements NavigableSet<E>, Cloneable, Serializable

A NavigableSet implementation based on a TreeMap. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).

Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.

Note that this implementation is not synchronized. If multiple threads access a tree set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be “wrapped” using the Collections.synchronizedSortedSet method. This is best done at creation time, to prevent accidental unsynchronized access to the set:

SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...));

TreeSet provides an implementation of the Set interface that uses a tree for storage. Objects are stored in sorted, ascending order. Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly.

The TreeSet class supports four constructors. The first form constructs an empty tree set that will be sorted in ascending order according to the natural order of its elements:

TreeSet( )
//The second form builds a tree set that contains the elements of c.
TreeSet(Collection c)

//The third form constructs an empty tree set that will be sorted according to the comparator specified by comp.
TreeSet(Comparator comp)

//The fourth form builds a tree set that contains the elements of ss:
TreeSet(SortedSet ss)

Methods in TreeSet:

SN Methods with Description
1 void add(Object o)
Adds the specified element to this set if it is not already present.
2 boolean addAll(Collection c)
Adds all of the elements in the specified collection to this set.
3 void clear()
Removes all of the elements from this set.
4 Object clone()
Returns a shallow copy of this TreeSet instance.
5 Comparator comparator()
Returns the comparator used to order this sorted set, or null if this tree set uses its elements natural ordering.
6 boolean contains(Object o)
Returns true if this set contains the specified element.
7 Object first()
Returns the first (lowest) element currently in this sorted set.
8 SortedSet headSet(Object toElement)
Returns a view of the portion of this set whose elements are strictly less than toElement.
9 boolean isEmpty()
Returns true if this set contains no elements.
10 Iterator iterator()
Returns an iterator over the elements in this set.
11 Object last()
Returns the last (highest) element currently in this sorted set.
12 boolean remove(Object o)
Removes the specified element from this set if it is present.
13 int size()
Returns the number of elements in this set (its cardinality).
14 SortedSet subSet(Object fromElement, Object toElement)
Returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive.
15 SortedSet tailSet(Object fromElement)
Returns a view of the portion of this set whose elements are greater than or equal to fromElement.

Example of TreeSet class:
The following program illustrates several of the methods supported by this collection:

import java.util.*;

public class TreeSetDemo {

   public static void main(String args[]) {
      // Create a tree set
      TreeSet ts = new TreeSet();
      // Add elements to the tree set
      ts.add("C");
      ts.add("A");
      ts.add("B");
      ts.add("E");
      ts.add("F");
      ts.add("D");
      System.out.println(ts);
   }
}

output:

Example of TreeSet adding duplicate value:

import java.util.*;

public class TreeSetDemo {

   public static void main(String args[]) {
      // Create a tree set
      TreeSet ts = new TreeSet();
      // Add elements to the tree set
      ts.add("Dinesh");
      ts.add("Anamika");
      ts.add("Sweety");
      ts.add("Anamika");
      ts.add("Sweety");
      ts.add("Raj");
      System.out.println(ts);
   }
}

output:

<<Previous <<   || Index ||   >>Next >>
Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

2 years ago