TreeSet is one of the implementations of the SortedSet interface in Java that uses a Red-black tree for storage. By default, the elements are stored in ascending order. It can also be ordered by a 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
// Java program to demonstrate the TreeSet import java.util.*; class Main { public static void main(String args[]) { // Creating and adding elements TreeSet<String> al = new TreeSet<String>(); // Add elements al.add( "Welcome" ); al.add( "to" ); al.add( "Geeks for Geeks" ); // Traversing elements Iterator<String> itr = al.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } } } |
Geeks for Geeks Welcome to
Sorted Set:
The SortedSet interface is available in java.util package which extends the Set interface. This interface contains the methods inherited from the Set interface and adds a feature that stores all the elements in this interface to be stored in a sorted manner.
Example:
Java
// Java program to demonstrate the // Sorted Set import java.util.*; class Main { public static void main(String[] args) { // create an instance of sortedset SortedSet<String> ts = new TreeSet<String>(); // Adding elements into the TreeSet // using add() ts.add( "Sravan" ); ts.add( "Ojaswi" ); ts.add( "Bobby" ); ts.add( "Rohith" ); ts.add( "Gnanesh" ); ts.add( "Devi2" ); // Adding the duplicate // element ts.add( "Sravan" ); // Displaying the TreeSet System.out.println(ts); // Removing items from TreeSet // using remove() ts.remove( "Ojaswi" ); // Iterating over Tree set items System.out.println( "Iterating over set:" ); Iterator<String> i = ts.iterator(); while (i.hasNext()) System.out.println(i.next()); } } |
[Bobby, Devi2, Gnanesh, Ojaswi, Rohith, Sravan] Iterating over set: Bobby Devi2 Gnanesh Rohith Sravan
Differences between TreeSet and SortedSet TreeSet SortedSet Syntax: TreeSet<String> treeset = new TreeSet<String>(); Syntax: It can not be instantiated as it is a InterfaceTreeSet is a concrete class. SortedSet is an interface. TreeSet allows a heterogeneous object. SortedSet allows a heterogeneous object. TreeSet maintains an object in sorted order. SortedSet maintains an object in sorted order.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.