Learnitweb

Comparator in Java

Comparator interface provides a way to control the sort order on some collection of objects. Comparator like Comparable interface imposes a total ordering on some collection of objects. Comparator can be used to control the order of certain data structures like sorted sets. Comparator can be used to provide an ordering for collections of objects that don’t have natural ordering.

Comparator can be passed to Collections.sort() and Arrays.sort() to control the sort order.

Comparator can be used to compare two objects based on different criteria or properties. For example, two Student class objects can be compared based on name, marks, roll number etc. One important thing to note that is that the Comparator is used to compare objects of same type.

Consistency with equals() method

The ordering imposed by Comparator should be consistent with equals method. The ordering imposed by Comparator is said to be consistent with equals method when the result of c.compare(obj1, obj2)==0 is same as obj1.equals(obj2). Here, c is the Comparator and obj1 and obj2 are the objects of some class to be compared. If this consistency is not maintained then some collections like sorted set behave unreliably.

compare method of Comparator

The signature of compare method is

int compare(T o1, T o2)

This method compares specified objects for order. This method returns

  • a negative integer if the first object is less than the second object.
  • a positive integer if the first object is greater than the second object.
  • zero, if the first object is equal to the second object.

The implementor should also ensure that following conditions are also met:

  • The result of compare(obj1, obj2) is of opposite sign of the result of compare(obj2, obj1). For example, if compare(obj1, obj2) returns 1 then compare(obj2, obj1) should return -1.
  • ((compare(obj1, obj2)>0) && (compare(obj2, obj3)>0)) should imply compare(obj1, obj3)>0.
  • If compare(obj1, obj2)==0 then obj1.equals(2) should also be equal to 0.

The compare method throws

  • NullPointerException if an argument is null.
  • ClassCastException if the arguments can not be compared if the type of arguments’ can not be compared.

Example of Comparator

In this example, we’ll create a Comparator and will use it to sort an ArrayList of Student objects. Student class has two fields, rollNo and totalMarks. The Comparator will sort the objects on the basis of totalMarks.

package com.learnitweb;

public class Student {
	private long rollNo;
	private int totalMarks;

	public Student(long rollNo, int totalMarks) {
		super();
		this.rollNo = rollNo;
		this.totalMarks = totalMarks;
	}

	public long getRollNo() {
		return rollNo;
	}

	public void setRollNo(long rollNo) {
		this.rollNo = rollNo;
	}

	public int getTotalMarks() {
		return totalMarks;
	}

	public void setTotalMarks(int totalMarks) {
		this.totalMarks = totalMarks;
	}

	@Override
	public String toString() {
		return "Student [rollNo=" + rollNo + ", totalMarks=" + totalMarks + "]";
	}
}
package com.learnitweb;

import java.util.Comparator;

public class StudentComparator implements Comparator<Student> {

	@Override
	public int compare(Student o1, Student o2) {
		if (o1.getTotalMarks() > o2.getTotalMarks())
			return 1;
		else if (o1.getTotalMarks() < o2.getTotalMarks())
			return -1;
		else
			return 0;
	}
}
package com.learnitweb;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ComparatorExample {

	public static void main(String args[]) throws InterruptedException {
		Student student1 = new Student(1, 450);
		Student student2 = new Student(2, 500);
		Student student3 = new Student(3, 600);

		List<Student> list = new ArrayList();
		list.add(student3);
		list.add(student2);
		list.add(student1);

		System.out.println("List before sort: " + list);

		// Use Comparator to sort the collection
		Collections.sort(list, new StudentComparator());

		System.out.println("List after sort: " + list);

	}
}