Comparator interface in Java

We will see what is comparator interface and how to use comparator interface in Java programming language.

For more information please go through http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html

A comparison function, which imposes a total ordering on some collection of objects. Comparator can be passed to a sort method (such as Collections.sort() or Arrays.sort()) to allow precise control over the sort order. Comparator 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.

Caution should be exercised when using a comparator capable of imposing an ordering inconsistent with equals to order a sorted set (or sorted map). Suppose a sorted set (or sorted map) with an explicit comparator c is used with elements (or keys) drawn from a set S. If the ordering imposed by c on S is inconsistent with equals, the sorted set (or sorted map) will behave strangely. In particular the sorted set (or sorted map) will violate the general contract for set (or map), which is defined in terms of equals.

The Class that implements Comparator interface must override the below method

int compare(T o1, T o2)

where,

o1 – the first object to be compared.
o2 – the second object to be compared.

The above method compares its two arguments for order and returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second, respectively.

We will now see how we can use Comparator interface in the following example.

Prerequisites

Knowledge of Java

Creating POJO Class

We will create a simple POJO class called Person that has three attributes – name, email, age.

In this example, we will compare few person objects based on their age, name and email.

So we will see how to use Comparator interface to compare objects.

package com.roytuts.java.comparator.example;

public class Person {

	private String name;
	private int age;
	private String email;

	public Person(String name, int age, String email) {
		this.name = name;
		this.age = age;
		this.email = email;
	}

	public String getName() {
		return name;
	}

	public int getAge() {
		return age;
	}

	public String getEmail() {
		return email;
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + ", email=" + email + "]";
	}

}

Comparison by Age

Create below class for comparing age between two person objects.

The compare() method takes two person objects and compares the persons based on their ages.

Related Posts:

The method returns value 0 (if two objects equal), positive integer (if first object is greater than second object), negative integer (if first object is less than second object).

package com.roytuts.java.comparator.example;

import java.util.Comparator;

public class PersonAgeComparator implements Comparator<Person> {

	@Override
	public int compare(Person p1, Person p2) {
		return p1.getAge() - p2.getAge();
	}

}

Comparison by Name

Create below class for comparing name between two person objects.

We are here using compareTo() or compareToIgnoreCase() method as we are comparing string objects (name).

package com.roytuts.java.comparator.example;

import java.util.Comparator;

public class PersonNameComparator implements Comparator<Person> {

	@Override
	public int compare(Person p1, Person p2) {
		return p1.getName().compareToIgnoreCase(p2.getName());
	}

}

Comparison by Email

Create below class for comparing email between two person objects.

We are here using compareTo() or compareToIgnoreCase() method as we are comparing string objects (email).

package com.roytuts.java.comparator.example;

import java.util.Comparator;

public class PersonEmailComparator implements Comparator<Person> {

	@Override
	public int compare(Person p1, Person p2) {
		return p1.getEmail().compareToIgnoreCase(p2.getEmail());
	}

}

Creating Main Class

We will create below main class to test the Comparator interface on various examples.

package com.roytuts.java.comparator.example;

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

public class ComparatorTest {

	public static void main(String[] args) {
		Person p1 = new Person("Ram", 20, "ram@email.com");
		Person p2 = new Person("Syam", 28, "syam@email.com");
		Person p3 = new Person("Jadu", 24, "jadu@email.com");
		Person p4 = new Person("Madhu", 32, "madhu@email.com");
		Person p5 = new Person("Ganesh", 30, "ganesh@email.com");

		List<Person> persons = new ArrayList<Person>();
		persons.add(p1);
		persons.add(p2);
		persons.add(p3);
		persons.add(p4);
		persons.add(p5);

		System.out.println("Comparison based on Name");

		Collections.sort(persons, new PersonNameComparator());

		persons.forEach(p -> System.out.println(p));

		System.out.println();

		System.out.println("Comparison based on Age");

		Collections.sort(persons, new PersonAgeComparator());

		persons.forEach(p -> System.out.println(p));

		System.out.println();

		System.out.println("Comparison based on Email");

		Collections.sort(persons, new PersonEmailComparator());

		persons.forEach(p -> System.out.println(p));
	}

}

Testing the Program

Run the above main class and you will see the below output in the console.

Comparison based on Name
Person [name=Ganesh, age=30, email=ganesh@email.com]
Person [name=Jadu, age=24, email=jadu@email.com]
Person [name=Madhu, age=32, email=madhu@email.com]
Person [name=Ram, age=20, email=ram@email.com]
Person [name=Syam, age=28, email=syam@email.com]

Comparison based on Age
Person [name=Ram, age=20, email=ram@email.com]
Person [name=Jadu, age=24, email=jadu@email.com]
Person [name=Syam, age=28, email=syam@email.com]
Person [name=Ganesh, age=30, email=ganesh@email.com]
Person [name=Madhu, age=32, email=madhu@email.com]

Comparison based on Email
Person [name=Ganesh, age=30, email=ganesh@email.com]
Person [name=Jadu, age=24, email=jadu@email.com]
Person [name=Madhu, age=32, email=madhu@email.com]
Person [name=Ram, age=20, email=ram@email.com]
Person [name=Syam, age=28, email=syam@email.com]

Another Approach

Updating Person Class

We will use the Comparator interface in the same POJO class to compare the person objects.

package com.roytuts.java.comparator.example;

import java.util.Comparator;

public class Person {

	private String name;
	private int age;
	private String email;

	public Person(String name, int age, String email) {
		this.name = name;
		this.age = age;
		this.email = email;
	}

	public String getName() {
		return name;
	}

	public int getAge() {
		return age;
	}

	public String getEmail() {
		return email;
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + ", email=" + email + "]";
	}

	public static final Comparator<Person> PersonNameComparator = new Comparator<Person>() {
		@Override
		public int compare(Person p1, Person p2) {
			return p1.getName().compareToIgnoreCase(p2.getName());
		}
	};

	public static final Comparator<Person> PersonAgeComparator = new Comparator<Person>() {
		@Override
		public int compare(Person p1, Person p2) {
			return p1.getAge() - p2.getAge();
		}
	};

	public static final Comparator<Person> PersonEmailComparator = new Comparator<Person>() {
		@Override
		public int compare(Person p1, Person p2) {
			return p1.getEmail().compareToIgnoreCase(p2.getEmail());
		}
	};

}

Updating Main Class

Update the main class as below:

package com.roytuts.java.comparator.example;

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

public class ComparatorTest {

	public static void main(String[] args) {
		Person p1 = new Person("Ram", 20, "ram@email.com");
		Person p2 = new Person("Syam", 28, "syam@email.com");
		Person p3 = new Person("Jadu", 24, "jadu@email.com");
		Person p4 = new Person("Madhu", 32, "madhu@email.com");
		Person p5 = new Person("Ganesh", 30, "ganesh@email.com");

		List<Person> persons = new ArrayList<Person>();
		persons.add(p1);
		persons.add(p2);
		persons.add(p3);
		persons.add(p4);
		persons.add(p5);

		System.out.println("Comparison based on Name");

		Collections.sort(persons, Person.PersonNameComparator);

		persons.forEach(p -> System.out.println(p));

		System.out.println();

		System.out.println("Comparison based on Age");

		Collections.sort(persons, Person.PersonAgeComparator);

		persons.forEach(p -> System.out.println(p));

		System.out.println();

		System.out.println("Comparison based on Email");

		Collections.sort(persons, Person.PersonEmailComparator);

		persons.forEach(p -> System.out.println(p));
	}

}

Running the above class will give you the same output in the console.

Source Code

You can download source code.

That’s all. Thank you for reading.

Leave a Reply

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