- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
TreeSet in Java
TreeSet provides an implementation of the Set interface that uses a tree for storage. Objects are stored in a sorted and ascending order. It contains only unique elements and the access & retrieval is quick.
Following is the list of the constructors supported by the TreeSet class.
Sr.No | Constructor & Description |
---|---|
1 | TreeSet( ) This constructor constructs an empty tree set that will be sorted in an ascending order according to the natural order of its elements. |
2 | TreeSet(Collection c) This constructor builds a tree set that contains the elements of the collection c. |
3 | TreeSet(Comparator comp) This constructor constructs an empty tree set that will be sorted according to the given comparator. |
4 | TreeSet(SortedSet ss) This constructor builds a TreeSet that contains the elements of the given SortedSet. |
Let us now see an example to work with TreeSet class −
Example
import java.util.*; public class Main { public static void main(String args[]) { TreeSet ts = new TreeSet(); // Add elements to the tree set ts.add("John"); ts.add("Kevin"); ts.add("Amy"); ts.add("Ryan"); ts.add("Katie"); ts.add("Tom"); System.out.println(ts); } }
Output
[Amy, John, Katie, Kevin, Ryan, Tom]
Let us now see another example wherein we are checking for the existence of an element in the TreeSet −
Example
import java.util.*; public class Main { public static void main(String args[]) { TreeSet ts = new TreeSet(); // Add elements to the tree set ts.add("John"); ts.add("Kevin"); ts.add("Amy"); ts.add("Ryan"); ts.add("Katie"); ts.add("Tom"); Iterator<String> i = ts.iterator(); while(i.hasNext()){ System.out.println(i.next()); } System.out.println("The Set has element 'Jacob'? = " + ts.contains("Jacob")); System.out.println("The Set has element 'Ryan'? = " + ts.contains("Ryan")); } }
Output
Amy John Katie Kevin Ryan Tom The Set has element 'Jacob'? = false The Set has element 'Ryan'? = true
- Related Articles
- Create a TreeSet in Java
- Java TreeSet Special Method
- Get last value in Java TreeSet
- Remove lowest element in Java TreeSet
- Remove highest element in Java TreeSet
- Get Size of TreeSet in Java
- Sort items in a Java TreeSet
- Get first value in Java TreeSet
- Convert HashSet to TreeSet in Java
- Get Sub Set from TreeSet in Java
- Get Tail Set from TreeSet in Java
- Iterate through elements of TreeSet in Java
- Remove specified element from TreeSet in Java
- Remove all elements from TreeSet in Java
- Set vs HashSet vs TreeSet in Java

Advertisements