How to Sort TreeSet Elements using Comparable Interface in Java?

TreeSet is an implementation of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a Set using their natural ordering whether an explicit comparator is provided.
To sort TreeSet elements using Comparable interface in java first, we create a class Student that implements the Comparable interface. In this class we override the compareTo() method.
Pseudo Code:
// Student class implements comparable interface
class Student implements Comparable<Student> {
Integer marks;
Student(Integer marks) {
this.marks = marks;
}
// override toString method
public String toString() {
return (" " + this.marks);
}
// Override compareTo method to sort LinkedHashSet in ascending order
public int compareTo(Student stu) {
return this.marks.compareTo(stu.marks);
}
}
Below is the implementation of the above approach:
Example 1:
Java
// Java program to demonstrate how to Sort TreeSet using// Comparable interface in ascending orderimport java.util.*;// Student class implements comparable interfaceclass Student implements Comparable<Student> { Integer marks; Student(Integer marks) { this.marks = marks; } // override toString method public String toString() { return (" " + this.marks); } // Override compareTo method to sort TreeSet in // ascending order public int compareTo(Student stu) { return this.marks.compareTo(stu.marks); }}class GFG { public static void main(String[] args) { // New TreeSet TreeSet<Student> set = new TreeSet<>(); // Adding elements to the set set.add(new Student(500)); set.add(new Student(300)); set.add(new Student(400)); set.add(new Student(100)); set.add(new Student(200)); // Print TreeSet sorted in ascending order System.out.println("Sort elements in ascending order : " + set); }} |
Output
Sort elements in ascending order : [ 100, 200, 300, 400, 500]
Example 2:
Java
// Java program demonstrate how to Sort TreeSet using// Comparable interface in descending orderimport java.util.*;// Student class implements comparable interfaceclass Student implements Comparable<Student> { Integer marks; Student(Integer marks) { this.marks = marks; } // override toString method public String toString() { return (" " + this.marks); } // Override compareTo method to sort TreeSet in // descending order public int compareTo(Student stu) { return stu.marks.compareTo(this.marks); }}class GFG { public static void main(String[] args) { // New TreeSet TreeSet<Student> set = new TreeSet<>(); // Adding elements to the set set.add(new Student(500)); set.add(new Student(300)); set.add(new Student(400)); set.add(new Student(100)); set.add(new Student(200)); // Print TreeSet sorted in descending order System.out.println("Sort elements in descending order : " + set); }} |
Output
Sort elements in descending order : [ 500, 400, 300, 200, 100]



