VOOZH about

URL: https://www.geeksforgeeks.org/java/how-to-sort-treeset-elements-using-comparable-interface-in-java/

⇱ How to Sort TreeSet Elements using Comparable Interface in Java? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Sort TreeSet Elements using Comparable Interface in Java?

Last Updated : 23 Jul, 2025

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:


Output
Sort elements in ascending order : [ 100, 200, 300, 400, 500]

Example 2: 


Output
Sort elements in descending order : [ 500, 400, 300, 200, 100]

 
 

Comment