// Java program to demonstrate how to Sort HashSet using
// Comparable interface
import java.util.*;
// 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 HashSet in
// descending order
public int compareTo(Student stu)
{
return stu.marks.compareTo(this.marks);
}
}
class GFG {
public static void main(String[] args)
{
// New HashSet
HashSet<Student> set = new HashSet<>();
// 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 Before sort
System.out.println("Before sort elements in descending order : "
+ set);
// TreeSet to sort HashSet using comparable
// interface
TreeSet<Student> tree_set = new TreeSet<>(set);
// Print after sorting
System.out.println("After sort elements in descending order : "
+ tree_set);
}
}
Before sort elements in descending order : [ 300, 400, 500, 200, 100]
After sort elements in descending order : [ 500, 400, 300, 200, 100]
+------------------------------------------------------------------------------------+
¦ Comparable ¦ Comparator ¦
¦-----------------------------------------+------------------------------------------¦
¦ java.lang.Comparable ¦ java.util.Comparator ¦
¦-----------------------------------------+------------------------------------------¦
¦ int objOne.compareTo(objTwo) ¦ int compare(objOne, objTwo) ¦
¦-----------------------------------------+------------------------------------------¦
¦ Negative, if objOne < objTwo ¦ Same as Comparable ¦
¦ Zero, if objOne == objTwo ¦ ¦
¦ Positive, if objOne > objTwo ¦ ¦
¦-----------------------------------------+------------------------------------------¦
¦ You must modify the class whose ¦ You build a class separate from to sort. ¦
¦ instances you want to sort. ¦ the class whose instances you want ¦
¦-----------------------------------------+------------------------------------------¦
¦ Only one sort sequence can be created ¦ Many sort sequences can be created ¦
¦-----------------------------------------+------------------------------------------¦
¦ Implemented frequently in the API by: ¦ Meant to be implemented to sort ¦
¦ String, Wrapper classes, Date, Calendar ¦ instances of third-party classes. ¦
+------------------------------------------------------------------------------------+