Difference between Comparable and Comparator
Comparable and Comparator both are interfaces and can be used to sort collection elements.
However, there are many differences between Comparable and Comparator interfaces that are given below.
Java Comparable Example
Let's see the example of a Comparable interface that sorts the list elements on the basis of age.
File: TestSort3.javaTest it Now
105 Jai 21 101 Vijay 23 106 Ajay 27
Java Comparator Example
Let's see an example of the Java Comparator interface where we are sorting the elements of a list using different comparators.Student.java AgeComparator.java NameComparator.java
This class provides comparison logic based on the name. In such case, we are using the compareTo() method of String class, which internally provides the comparison logic.TestComparator.java
In this class, we are printing the values of the object by sorting on the basis of name and age.
Sorting by Name 106 Ajay 27 105 Jai 21 101 Vijay 23 Sorting by Age 105 Jai 21 101 Vijay 23 106 Ajay 27