What is the difference between Comparable and Comparator in Java?

PointComparableComparator
Packagejava.langjava.util
MethodcompareTo(T other)compare(T a, T b)
WhereInside the classA separate object or lambda
OrdersOne natural orderMany orders
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Main {
    record Student(String name, int marks) implements Comparable<Student> {
        @Override
        public int compareTo(Student other) {
            return this.name.compareTo(other.name);      // natural order: by name
        }
    }

    public static void main(String[] args) {
        List<Student> list = new ArrayList<>(List.of(new Student("Meera", 95), new Student("Aman", 72), new Student("Riya", 88)));

        java.util.Collections.sort(list);                        // uses compareTo
        System.out.println(list);

        list.sort(Comparator.comparingInt(Student::marks).reversed());   // another order
        System.out.println(list);
    }
}
Output

[Student[name=Aman, marks=72], Student[name=Meera, marks=95], Student[name=Riya, marks=88]]
[Student[name=Meera, marks=95], Student[name=Riya, marks=88], Student[name=Aman, marks=72]]


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.