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. 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.

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)

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

Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

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

Prerequisites

The following things are required in order to run the application

Eclipse Helios
JDK 1.6 or higher

Step 1. Create the below POJO class

package com.roytuts.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 void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	@Override
	public String toString() {
		return "Name : " + name + ", Age : " + age + ", Email : " + email;
	}
}

Step 2. Create below class for comparing age between two employee objects

package com.roytuts.comparator;

import java.util.Comparator;

public class PersonAgeComparator implements Comparator<Person> {

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

}

Step 3. Create below class for comparing name between two employee objects

package com.roytuts.comparator;

import java.util.Comparator;

public class PersonNameComparator implements Comparator<Person> {

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

}

Step 4. Create below class for comparing email between two employee objects

package com.roytuts.comparator;

import java.util.Comparator;

public class PersonEmailComparator implements Comparator<Person> {

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

}

Step 5. Create a below test class

package com.roytuts.comparator;

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());
		for (Person person : persons) {
			System.out.println(person);
		}
		System.out.println("Comparison based on Age");
		Collections.sort(persons, new PersonAgeComparator());
		for (Person person : persons) {
			System.out.println(person);
		}
		System.out.println("Comparison based on Email");
		Collections.sort(persons, new PersonEmailComparator());
		for (Person person : persons) {
			System.out.println(person);
		}
	}

}

Step 6. Run the above class and see the below output in the console.

Comparison based on Name
Name : Ganesh, Age : 30, Email : ganesh@email.com
Name : Jadu, Age : 24, Email : jadu@email.com
Name : Madhu, Age : 32, Email : madhu@email.com
Name : Ram, Age : 20, Email : ram@email.com
Name : Syam, Age : 28, Email : syam@email.com
Comparison based on Age
Name : Ram, Age : 20, Email : ram@email.com
Name : Jadu, Age : 24, Email : jadu@email.com
Name : Syam, Age : 28, Email : syam@email.com
Name : Ganesh, Age : 30, Email : ganesh@email.com
Name : Madhu, Age : 32, Email : madhu@email.com
Comparison based on Email
Name : Ganesh, Age : 30, Email : ganesh@email.com
Name : Jadu, Age : 24, Email : jadu@email.com
Name : Madhu, Age : 32, Email : madhu@email.com
Name : Ram, Age : 20, Email : ram@email.com
Name : Syam, Age : 28, Email : syam@email.com

We can also do the same thing in different way as shown below.

Create the POJO class with below source code

package com.roytuts.comparator;

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 void setName(String name) {
    this.name = name;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public String getEmail() {
    return email;
  }

  public void setEmail(String email) {
    this.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());
    }
  };

  @Override
  public String toString() {
    return "Name : " + name + ", Age : " + age + ", Email : " + email;
  }
}

Create the below test class

package com.roytuts.comparator;

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);
    for (Person person : persons) {
      System.out.println(person);
    }
    System.out.println("Comparison based on Age");
    Collections.sort(persons, Person.PersonAgeComparator);
    for (Person person : persons) {
      System.out.println(person);
    }
    System.out.println("Comparison based on Email");
    Collections.sort(persons, Person.PersonEmailComparator);
    for (Person person : persons) {
      System.out.println(person);
    }
  }

}

Run the above class and see the below output in the console

Comparison based on Name
Name : Ganesh, Age : 30, Email : ganesh@email.com
Name : Jadu, Age : 24, Email : jadu@email.com
Name : Madhu, Age : 32, Email : madhu@email.com
Name : Ram, Age : 20, Email : ram@email.com
Name : Syam, Age : 28, Email : syam@email.com
Comparison based on Age
Name : Ram, Age : 20, Email : ram@email.com
Name : Jadu, Age : 24, Email : jadu@email.com
Name : Syam, Age : 28, Email : syam@email.com
Name : Ganesh, Age : 30, Email : ganesh@email.com
Name : Madhu, Age : 32, Email : madhu@email.com
Comparison based on Email
Name : Ganesh, Age : 30, Email : ganesh@email.com
Name : Jadu, Age : 24, Email : jadu@email.com
Name : Madhu, Age : 32, Email : madhu@email.com
Name : Ram, Age : 20, Email : ram@email.com
Name : Syam, Age : 28, Email : syam@email.com

That’s all. Thank you for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

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