In this article, we will compare 2 important interface in collection framework i.e.; Comparable v/s Comparator
- Comparable interface
- Comparator interface
Both interface is used to sort collection elements
1. Comparable v/s Comparator:
|Comparable interface||Comparator interface|
|Present in java.lang package||Present in java.util package|
|Defines only one important method i.e.;
public int compareTo(Object obj);
|Defines 2 method i.e.;
public int compare(Object obj1, Object obj2);
public boolean equals(Object object);
|It is basically used for default natural sorting order [DNSO]||This is preferred for customized sorting order [CSO]|
|This interface need to be implemented in the same class for which sorting is required||Separate class is required to implement Comparator interface|
|Elements of List can be sorted using comparable interface using sort(); method of Collections class, as shown below
|Elements of List can be sorted using comparator interface using sort(); method of Collections class, as shown below
Example: Collection.sort(listItems, comparator);
|String & wrapper classes’ like Integer, Double, etc implement comparable interface||There are very few classes’ which implements Comparator interface|
2. Example on Comparable and Comparator interface:
Related Articles :
- Converting Unordered HashMap into Sorted TreeMap
- Sorting HashMap by Keys and Values
- Java 8 – How to Sort HashMap entries by its Keys – 6 ways ?
- Java 8 – How to Sort HashMap entries by its Values – 6 ways ?
- Java 8 – Sorting HashMap by Keys and Values using Stream
- How to sort LinkedHashMap by its Keys ?
- How to sort LinkedHashMap by its Values ?
- Java – How to Sort TreeMap by it Keys in descending order ?
- Sorting Hashtable contents
- Java 8 – How to sort ArrayList elements
- Java 8 – Sorting List of primitive, String & Custom Objects
- Java 8 – Sorting ArrayList using sort() method of List
- Java 8 – How to sort LinkedList elements
- Java 8 – How to sort HashSet elements
- Java 8 – How to sort LinkedHashSet elements
- Java 8 – How to sort TreeSet in descending order
- Java 8 – How to sort List and Arrays with null values present
- Java 8 – How to sort Arrays in Ascending and Descending order ?
- Java 8 – Sorting list of objects on multiple fields (3-level attributes)
Happy Coding !!
Happy Learning !!