Comparable vs Comparator in Java
Posted By : Aryan Chaurasia | 30-Mar-2022
Comparable Object
A comparable object is capable of comparing itself with another object, therefore, it is called comparable Object.
Steps of using Comparable Object.
1 . implements Comparable Methods
-: implements Comparable<>
2 . @Override compareTo() methods
-: @Override
public int compareTo() {}
3. For print we Override toString() methods.
@Override
public String toString(){
}
Code :-
public static void main(________){
List<Studsent>students = new ArrayList<>();
students.add(new Student(23,"Ram",25));
students.add(new Student(24,"Shyam",26));
students.add(new Student(25,"RamLal",28));ns,
Collections.sort(students);
students.forEach(System.out::println);
}
1st Way
@Override
public int compareTo(Student obj){
if(this.marks>obj.marks){
return -1;
}
else if(this.marks<obj.marks){
return 1;
}else{
return this.name.compareTo(obj.name);
}
}
Comparator Object
with the help of Comparator we give the flexibility to sort in any order.
in Comparator compare(Student s1,Student s2){} method
1 . implements Comparator Methods
-: implements Comparable<>
2 . @Override compare() methods
-: @Override
public int compare() {}
3. For print we Override toString() methods.
@Override
public String toString(){
}
@Override
public int compare(Student s1,Student s2){
if(o1.name.equals(o2.name)){
return o1.marks- o2.marks;
}
else{
return o1.name.compareTo(o2.name);
}
}
In Java 8
Collections.sort(Students,(o1,o2)->o1.name.compareTo(o2.name))
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Aryan Chaurasia
Aryan is Java Devloper And Has Good Knowledge of Data Structure ,Java , Mysql & SpringBoot