When we have to sort collection of custom objects or sort on multiple fields, then we need to provide JAVA with the custom strategy for comparison. This can be done easily using Comparator Interface and overriding its compare() method.
There are two ways to achieve this, one is using Anonymous Class and second way it to implement the interface and create the object of this class.Both of which are explained below.
In the following example, we have a custom object of Node class. Node class has two members
viz. data and abc We want to sort the collection/list of Node objects using the strategy:
-Node a > Node b if a.data > b.data
-Node a > Node b if a.abc > b.abc && a.data==b.data
As we have a custom comparison strategy, we need to provide custom comparator to sort method of Collection.
Custom Comparator using Anonymous class
Implementing Comparator interface
Important thing to REMEMBER
The order in which you subtract the two objects inside compare method is very crucial!
If the compare method is defined as:
public int compare(Object obj1 , Object obj2 ) {..}
Then, →
If you want to sort obj1 and obj2 in ascending order, we return obj1 - obj2
If you want to sort obj1 and obj2 in descending order, we return obj2 - obj1
Comments