Comparator in java with Example

Comparator is an Interface in java which is present in java.util package.

Comparator interface has only method comapare which has two argument.

1
2
3
4
5
6
7
 
 
public int compare(Object o1, Object o2){
 
//Logic to compare two object
 
}

A comparison function, which imposes a total ordering on some collection of objects.

Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don’t have a natural
ordering
.

The ordering imposed by a comparator c on a set of elements S is said to be consistent with equals if and only if c.compare(e1, e2)==0 has the same boolean value as e1.equals(e2) for every e1 and e2 in S.

Let’s Understand using Example.

Sorting ArrayList element based on last digit of element.

 
SortNumber.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package Comaprator;
 
import java.util.Comparator;
 
public class SortNumber implements Comparator<Integer>
{
 
	@Override
	public int compare(Integer o1, Integer o2) {
 
		if(o1%10>o2%10)
			return 1;
 
		return -1;
	}
}

Comaprator.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package Comaprator;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
 
public class Comaprator
{
	public static void main(String[] args) 
	{
 
		//Integer arraylist
 
		ArrayList<Integer> list=new ArrayList<Integer>();
 
		list.add(533);
		list.add(224);
		list.add(111);
		list.add(325);
		list.add(495);
 
		Comparator<Integer> comp=new SortNumber();
 
		Collections.sort(list, comp);
 
		for (Integer integer : list) 
		{
 
			System.out.println(integer);
 
		}
 
	}
}

Output:
111
533
224
495
325

Leave a Reply

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