TreeSet in Java

Posted on Updated on

TreeSet provides an implementation of the SortedSet Interface and SortedSet extends Set Interface. It behaves like simple set with the exception that it stores elements in sorted format.Following are the features of TreeSet.

  1. TreeSet uses tree data structure for storage.
  2. Objects are stored in sorted, ascending order. But we can iterate in descending order using method TreeSet.descendingIterator().
  3. Access and retrieval times are very fast which make TreeSet an excellent choice for storage of large volume of data in sorted format.

TreeSet provides following constructors.

Construtor Description
TreeSet() Default construtor
TreeSet(Collection c) Creates object of TreeSet using elements of collection c.
TreeSet(Comparator comp) Creates object of TreeSet that will be sorted according to the comparator specified by comp.
TreeSet(SortedSet ss) Creates object of TreeSet that contains the elements of ss.

Example of TreeSet.

Output

[HashSet, LinkedHashSet, Set, SortedSet]

Example to Iterate TreeSet in ascending and descending order.

Output

Iterating TreeSet In Ascending Order :
HashSet
LinkedHashSet
Set
SortedSet
Iterating TreeSet In Decending Order :
SortedSet
Set
LinkedHashSet
HashSet

Exmaple of TreeSet to store custom class Emp.

Output

Content of TreeSet
[1 : Michael, 2 : Joseph, 3 : Charles, 4 : Jhonson]

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.