Clean • Professional
Sorting objects in Java can be done using Comparable and Comparator interfaces. Both are part of the java.util package and widely used in collections like ArrayList, TreeSet, TreeMap, etc.
Comparable is used to define a natural ordering of objects by modifying the class itself.
java.langint compareTo(T obj)public class Student implements Comparable<Student> {
private String name;
private int marks;
public Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
@Override
public int compareTo(Student other) {
return this.marks - other.marks; // Ascending order
}
@Override
public String toString() {
return name + " : " + marks;
}
}
Usage:
ArrayList<Student> list = new ArrayList<>();
list.add(new Student("Alice", 90));
list.add(new Student("Bob", 75));
Collections.sort(list);
System.out.println(list);
compareTo() method.this < objthis == objthis > objComparator is used to define custom ordering without modifying the class.
java.utilint compare(T o1, T o2) and boolean equals(Object obj)(Anonymous Class):
Comparator<Student> cmp = new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
return s2.getMarks() - s1.getMarks(); // Descending order
}
};
Collections.sort(list, cmp);
Syntax (Lambda in Java 8+):
list.sort((s1, s2) -> s2.getMarks() - s1.getMarks());
compare() method.| Feature | Comparable | Comparator |
|---|---|---|
| Purpose | Defines natural ordering of objects | Defines custom ordering of objects |
| Interface | java.lang.Comparable | java.util.Comparator |
| Method | compareTo(Object o) | compare(Object o1, Object o2) |
| Implemented by | Class whose objects need to be sorted | Separate class or lambda (external logic) |
| Number of Sorts | Single sort sequence | Multiple sort sequences possible |
| Location | Inside the class | Outside the class |
| Usage | Collections.sort(list) | Collections.sort(list, comparator) |
| Example | class Student implements Comparable<Student> | class AgeComparator implements Comparator<Student> |
import java.util.*;
class Student implements Comparable<Student> {
String name;
int marks;
public Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
@Override
public int compareTo(Student other) {
return this.marks - other.marks; // Ascending
}
@Override
public String toString() {
return name + ":" + marks;
}
}
public class Main {
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<>();
list.add(new Student("Alice", 90));
list.add(new Student("Bob", 75));
list.add(new Student("Charlie", 85));
// Natural Order (Comparable)
Collections.sort(list);
System.out.println("Ascending by marks: " + list);
// Custom Order (Comparator)
list.sort((s1, s2) -> s2.marks - s1.marks);
System.out.println("Descending by marks: " + list);
}
}
Output:
Ascending by marks: [Bob:75, Charlie:85, Alice:90]
Descending by marks: [Alice:90, Charlie:85, Bob:75]