Difference between Comparable and ComparatorComparable 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 ExampleLet's see the example of a Comparable interface that sorts the list elements on the basis of age. File: TestSort3.java Test it NowOutput: 105 Jai 21 101 Vijay 23 106 Ajay 27 Java Comparator ExampleLet's see an example of the Java Comparator interface where we are sorting the elements of a list using different comparators. Student.javaAgeComparator.javaNameComparator.javaThis 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.javaIn this class, we are printing the values of the object by sorting on the basis of name and age. Output: Sorting by Name 106 Ajay 27 105 Jai 21 101 Vijay 23 Sorting by Age 105 Jai 21 101 Vijay 23 106 Ajay 27 Next TopicProperties in Java |