Comparable vs Comparator in Java

Connect with

Comparable vs Comparator in javaLearn Comparable vs Comparator in Java. Both java.lang.Comparable and java.util.Comparator are used to sort the list of Java custom objects in natural and custom sorting respectively.

1. overview of Comparable vs Comparator in Java

Both are interfaces java.util.Comparable and java.util.Comparator used for sorting the List of java custom objects. Objective of this sort is to save the network call, by sort in our middle layer component i.e. business logic. There can be two types of sorting: for natural sorting and for custom sorting.

2. Key Points of Comparable

  • This is in side the java.lang package.
  • This is used to sort in natural order.
  • only one logic of sorting by implements Comparable, it means only one sorting on any one property.
  • you must have to implements Comparable in POJO/domain object.

Comparable Interface:

public interface Comparable {
    int compareTo(T object);
}

3. Key Points of Comparator

  • This Comparator interface is in side the java.util package.
  • This is used to sort in non-natural order, it means to sort on complex order.
  • There can be multiple logic of sorting on multiple property.
  • No need to implements Comparator in POJO/domain object. Although you can write default sorting by implementing comparator in in POJO class.

Interface Comparator.java

public interface Comparator {
    int compare(T object1, T object2);
}

4. Comparison of Comparable and Comparator

Following are the comparative study about java.lang.Comparable and java.util.Comparator

java.lang.Comparablejava.util.Comparator
package this is in java.langComparator is in java.util package
used for natural sortingComparator is used for complex sorting , i.e. non-natural sorting
implementsComparable interface have to implements in POJOno need to implements Comparator interface in POJO
sortingCollections.sort(list) method to sortCollections.sort(list, comparator) method to sort, second parameter is comparator which can provide any of the either anonymous class, named class or method which returns a comparator object.
methodcompareTo() method need to overridecompare(T object1, T object2) method need to override.

5. Reference

comparable Java Oracle

6. Related Post

By the way, if you have not visted other sorting posts, you must visit following:

  • How to sort list of object using Comparable in Java
  • How to sort list of object using Comparator in Java
  • Sorting of stack in java
  • Sorting of Array using Java.util.Arrays in Java
  • Your comments are welcome to improve this post about comparable vs comparator in java 🙂


    Connect with

    1 thought on “Comparable vs Comparator in Java”

    Leave a Comment

    Your email address will not be published. Required fields are marked *