public interface Comparable<T> {
public int compareTo(T o);
}
Comparable & Comparator in Java
Upasana | November 21, 2020 | 3 min read | 1,469 views
Java provides two mechanisms to compare objects:
-
Using Comparable interface
-
Using Comparator interface
The purpose for using one of these interface depends upon the usecase. We will discuss both the approaches one by one.
Using Comparable Interface
When we implement comparable interface in a class, it imposes a total ordering on its objects. This ordering is referred to as the class’s natural ordering, and the class’s compareTo
method is referred to as its natural comparison method.
Following is the definition for this interface.
Few important points:
-
Lists of objects that implement this interface can be sorted automatically by
Collections.sort
orArrays.sort
-
Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without need to specify a comparator.
Example
class Person implements Comparable<Person>{
int age;
String name;
String email;
@Override
public int compareTo(Person o) {
return name.compareTo(o.getName());
}
}
Now we can sort a collection of persons based on its natural ordering using Collections.sort
method.
List<Person> students = Arrays.asList(
new Person(20,"Bob", "bob@mail.com"),
new Person(19, "Jane", "Jane@mail.com"),
new Person(21,"Foo", "foo@mail.com")
);
Collections.sort(students);
Bob
Foo
Jane
Using Comparator Interface
A comparison function, which imposes a total ordering on some collection of objects.
@FunctionalInterface
public interface Comparator<T> {
int compare(T o1, T o2);
}
-
Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. We can have more than one Comparator for a given class, for example Person class may have two different comparators, one that sorts based on name and another based on age.
-
Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don’t have a natural ordering.
Example
Lets define two comparators now, one for name based comparison and another on basis of age.
class NameComparator implements Comparator<Person> {
@Override
public int compare(Person o1, Person o2) {
return o1.name.compareTo(o2.name);
}
}
class AgeComparator implements Comparator<Person> {
@Override
public int compare(Person o1, Person o2) {
return ((Integer)o1.age).compareTo(o2.age);
}
}
Now we can specify one of the above defined sorting function to choose sorting on demand:
List<Person> students = Arrays.asList(
new Person(20,"Bob"),
new Person(19, "Jane"),
new Person(21,"Foo")
);
Collections.sort(students, new AgeComparator());
Similarly, we can sort based on NameComparator as well.
Java 8 style comparator using lambda approach
Java 8’s lambda can be used to write inline comparator and even chain them as and when required.
List<Person> students = Arrays.asList(
new Person(20,"Foo"),
new Person(19, "Jane"),
new Person(21,"Foo")
);
Collections.sort(students);
students.stream()
.sorted(Comparator
.comparing(Person::getName)
.thenComparing(Person::getAge)
).forEach(System.out::println);
That’s all for this article.
Top articles in this category:
- Java Coding Problems for SDET Automation Engineer
- 50 Java Interview Questions for SDET Automation Engineer
- Junit interview questions for SDET automation engineer
- Rest Assured API Testing Interview Questions
- Difference between Enumeration and Iterator in Java
- Anagrams string checker in Java
- JUnit 5 Parameterized Tests