Java TreeSet

Java TreeSet is similar to HashSet except it sorts the TreeSet entries in ascending order.

TreeSet class is not synchronized. 

TreeSet is an implementation of self balancing binary search tree. It is more efficient to store huge sorted data and perform multiple operations. Printing n elements will take O(N) time in TreeSet.

add, remove, and search operations takes O(log(N)) time.

TreeSet class implements NavigableSet interface which internally extends SortedSet interface.

Constructors:

  1. The below expression will create empty TreeSet having all the entries sorted by ascending order

TreeSet treeSet = new TreeSet (); 

2. The below expression will create TreeSet with other collections.

TreeSet treeSet = new TreeSet(Collection collection);

3. The below expression will create TreeSet with SortedSet.

TreeSet t = new TreeSet(SortedSet s);

Example:

TreeSet Methods:

Below are some of the methods from TreeSet class.

add(): Method helps us to add an element in TreeSet.

remove(): Method helps us to remove an element from TreeSet.

size(): Method returns the number of element in TreeSet Collection.

remove(): Method helps us to remove an element from TreeSet.

contains(): Method returns true if specified element present in TreeSet collection else return false.

clear(): Method helps us to remove all the elements from TreeSet.

isEmpty(): Method returns true if number of elemetns is zero else return false.

Imran Khan

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

📝 Blogs

📧 Imran Khan