Difference Between TreeSet and SortedSet in Java
TreeSet is one of the implementations of the Navigable sub-interface. It is underlying data structure is a red-black tree. The elements are stored in ascending order and more methods are available in TreeSet compare to SortedSet. We can also change the sorting parameter using a Comparator. For example, Comparator provided at set creation time, depending on which constructor is used.
- It also implements NavigableSet interface.
- NavigableSet extends SortedSet and Set interfaces.
Example
Java
import java.util.*;
class GFG {
public static void main(String args[]) {
TreeSet<String> al = new TreeSet<String>();
al.add( "Welcome" );
al.add( "to" );
al.add( "Geeks for Geeks" );
Iterator<String> itr = al.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
|
Output
Geeks for Geeks
Welcome
to
Sorted Set
The SortedSet is a sub-interface, which is available in java.util.package which extends the Set interface. This interface contains the methods inherited from the Set interface. For example, headSet, tailSet, subSet, Comparator, first, last, and many more.
Example
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
SortedSet<String> ts = new TreeSet<String>();
ts.add( "Sravan" );
ts.add( "Ojaswi" );
ts.add( "Bobby" );
ts.add( "Rohith" );
ts.add( "Gnanesh" );
ts.add( "Devi2" );
ts.add( "Sravan" );
System.out.println(ts);
ts.remove( "Ojaswi" );
System.out.println( "Iterating over set:" );
Iterator<String> i = ts.iterator();
while (i.hasNext())
System.out.println(i.next());
}
}
|
Output
[Bobby, Devi2, Gnanesh, Ojaswi, Rohith, Sravan]
Iterating over set:
Bobby
Devi2
Gnanesh
Rohith
Sravan
Now after having adequate understanding and internal working of both TreeSet and SortedSet, now let us see the differences between TreeSet and SortedSet which is as depicted from the table provided below as follows:
Basis |
TreeSet
|
SortedSet
|
Classification |
Class of NavigableSet sub-interface. |
Sub-Interface |
Insertion Order |
TreeSet maintains an object in sorted order. |
SortedSet maintains an object in sorted order. |
Initialization |
Syntax:
TreeSet<Datatype> treeset = new TreeSet<>();
|
Syntax:
It can not be instantiated as it is a sub-Interface.
|
Methods |
Contains more methods than SortedSet. |
Contains fewer methods than TreeSet. |
Example |
contains all the methods of SortSet. In addition methods like ceiling(), floor(), higher(), lower() and e.t.c |
contains methods like add(), addAll(), iterator(), retainAll() and e.t.c |
Conclusion: Basically in simple words let’s assume this way, TreeSet is a class of NavigableSet which contains all of the methods for better traversing and searching for values. SortedSet is a sub-set of NavigableSet in terms of methods compare to TreeSet(NavigableSet)
Last Updated :
01 Nov, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...