Learn 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.Comparable | java.util.Comparator | |
package | this is in java.lang | Comparator is in java.util package |
used for natural sorting | Comparator is used for complex sorting , i.e. non-natural sorting | |
implements | Comparable interface have to implements in POJO | no need to implements Comparator interface in POJO |
sorting | Collections.sort(list) method to sort | Collections.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. |
method | compareTo() method need to override | compare(T object1, T object2) method need to override. |
5. Reference
6. Related Post
By the way, if you have not visted other sorting posts, you must visit following:
Your comments are welcome to improve this post about comparable vs comparator in java 🙂
This good one , Please post some for NodeJs too