Comparable vs Comparator in java

Connect with

Oracle JavaBoth the interfaces java.lang.Comparable and java.util.Comparator are used to sort the list of Java Custom objects.

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);
}

Key Points of Comparator

  • This 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

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

Comparison of Comparable and Comparator

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

[table “” not found /]

Related Post:

Your comments are welcome to improve this post. 🙂


Connect with

1 thought on “Comparable vs Comparator in java

Leave a Reply

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