Comparator Interface and how to use it

Ever since I started learning Java, Comparator Interface has been one of the ghosting topic to me.
Beacause I really don't know how to use it.
I just have a general knowledge that it has compare function which we need to implement.
So now i got a clear idea of what it is....... so wanted to help people like me..

Comparator - Interface :
It is used to order objects(primitives also) based on user defined logic.
It has a compare function which we need to override.
generally, this comparator inteface is used along with the sort function i.e., to sort based on some user defined logic.

lets assume   String a=["x","a","y","c","b"]

when we use

Arrays.sort(a);

now the values will be in ascending order.

lets first understand how ascending order can be generated using comparators
and then this can be generalised for descending orders as well.

 String s=["x","a","y","c","b"];
 
 Comparator<String> comp = new Comparator<String>(){
		    @Override
		    public int compare(String a, String b){
				return a.compareTo(b);  
		    }
	     };
Arrays.sort(s,comp);
	
// the above code can also be written in lamba expression as
Arrays.sort(s,(a,b)->a.compareTo(b));

compare function - tells how to compare two objects in particualr strings here.
and now we need a detailed understanding of compareTo function

//the general syntax of compareTo is  a.compareTo(b)
//below shows the detailed descriptioin of how compareTo works assuming a and b are two objects
	if a > b, it returns positive number  
	if a < b, it returns negative number  
	if a == b, it returns 0  
	
// if a=3 and b=6 so if we compare a and b then negative number is returned which means a should be before b in ordering 

but we want descending order. So we need the above modifications when we take two objects a and b into consideration

	if b > a, it returns positive number  
	if b < a, it returns negative number  
	if b == a, it returns 0  
	
	//if a=3 and b=6 so if we compare a and b then positive number is returned which means a should be after b in ordering which is correct for descending order.

If you take a clear look at above two implementations we can come to conclusion that:

we need to just interchange a and b  
Arrays.sort(s,b.compareTo(a)); //returns descending order of array

So all we need here is to have a clear understanding of compareTo and how to use it

And after reading try solving
https://leetcode.com/problems/largest-number/
So that you can get even clear understanding

Hope you got it..!!

Comments (2)