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
import java.util.*;
class Student implements Comparable<Student> {
Integer marks;
Student(Integer marks) { this .marks = marks; }
public String toString() { return ( " " + this .marks); }
public int compareTo(Student stu)
{
return this .marks.compareTo(stu.marks);
}
}
class GFG {
public static void main(String[] args)
{
TreeSet<Student> set = new TreeSet<>();
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 ));
System.out.println( "Sort elements in ascending order : " + set);
}
}
|
Output
Sort elements in ascending order : [ 100, 200, 300, 400, 500]
Example 2:
Java
import java.util.*;
class Student implements Comparable<Student> {
Integer marks;
Student(Integer marks) { this .marks = marks; }
public String toString() { return ( " " + this .marks); }
public int compareTo(Student stu)
{
return stu.marks.compareTo( this .marks);
}
}
class GFG {
public static void main(String[] args)
{
TreeSet<Student> set = new TreeSet<>();
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 ));
System.out.println( "Sort elements in descending order : " + set);
}
}
|
Output
Sort elements in descending order : [ 500, 400, 300, 200, 100]
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
01 Oct, 2021
Like Article
Save Article