Konstantina Dimtsa

About Konstantina Dimtsa

Konstantina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she is currently pursuing M.Sc studies in Advanced Information Systems at the same department. She is also working as a research associate for NKUA in the field of telecommunications. Her main interests lie in software engineering, web applications, databases and telecommunications.

Java Comparator Example

In this example we will show how to use java.util.Comparator interface. java.util.Comparator is an interface which is used for sorting objects in Java. The compare(Object o1, Object o2) method of Comparator interface needs to be implemented for this purpose, which compares two objects and returns an integer, depending on the comparison: positive, if o1 is greater than o2; zero, if o1 equals to o2; negative, if o1 is less than o1. Another interface which is used for sorting objects is java.lang.Comparable. However, Comparable cannot sort objects on different attributes, while Comparator can. Also, the method compareTo(T o) of Comparable needs to be implemented in this case, which compares the current object (this object) with the specified object for order. In this example, we will pay attention to Comparator interface.

1. Example of using Comparator interface

We need to use Comparator interface when we want to order objects on different attributes, for example, let’s suppose that an employer would like to order his employees by salary or by name. This cannot be done using Comparable interface.

So, let’s see an example. First of all, let’s create the class that will represent the object that will be sorted. Create a java class named Student.java with the following code:

Student.java

package com.javacodegeeks.java.util.comparator;

public class Student {
	private String name;
	private int age;
	private String lesson;
	private int grade;

	public Student() {
	}

	public Student(String name, int age, String lesson, int grade) {
		super();
		this.name = name;
		this.age = age;
		this.lesson = lesson;
		this.grade = grade;
	}

	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 getLesson() {
		return lesson;
	}

	public void setLesson(String lesson) {
		this.lesson = lesson;
	}

	public int getGrade() {
		return grade;
	}

	public void setGrade(int grade) {
		this.grade = grade;
	}

	@Override
	public String toString() {
		return "[name=" + this.name + ", age=" + this.age + ", lesson="
				+ this.lesson + ", grade=" + this.grade + "]";
	}

}

Now, let’s create two classes that will implement the Comparator interface and they will be used so as to sort students with different attributes.
Firstly, create a java class named GradeComparator.java with the following code:

GradeComparator.java

package com.javacodegeeks.java.util.comparator;

import java.util.Comparator;

public class GradeComparator implements Comparator {

	@Override
	public int compare(Student o1, Student o2) {

		// descending order (ascending order would be:
		// o1.getGrade()-o2.getGrade())
		return o2.getGrade() - o1.getGrade();
	}

}

The above class will sort students by grade, in descending order.
Then, create a java class named NameComparator.java with the following code:

NameComparator.java

package com.javacodegeeks.java.util.comparator;

import java.util.Comparator;

public class NameComparator implements Comparator {

	@Override
	public int compare(Student o1, Student o2) {
		String name1 = o1.getName();
		String name2 = o2.getName();

		// ascending order (descending order would be: name2.compareTo(name1))
		return name1.compareTo(name2);
	}

}

This class will sort students by Name, in ascending order.

As we mentioned above, classes that implement the Comparator interface need to override the compare() method. In this specific example, the sorting of grades will be in descending order as we have reversed the objects o1, o2. For the comparison of names, we used the int compareTo(String anotherString) method.

Finally, create a java class named MainComparatorExample.java, which will be the main class of our example:

MainComparatorExample.java

package com.javacodegeeks.java.util.comparator;

import java.util.Arrays;

public class MainComparatorExample {

	public static void main(String args[]) {
		Student student[] = new Student[3];

		student[0] = new Student();
		student[0].setName("Nick");
		student[0].setGrade(19);

		student[1] = new Student();
		student[1].setName("Helen");
		student[1].setGrade(12);

		student[2] = new Student();
		student[2].setName("Ross");
		student[2].setGrade(16);

		System.out.println("Order of students before sorting is: ");

		for (int i = 0; i < student.length; i++) {
			System.out.println(student[i].getName() + "\t"
					+ student[i].getGrade());
		}

		Arrays.sort(student, new GradeComparator());
		System.out
				.println("Order of students after sorting by student grade is");

		for (int i = 0; i < student.length; i++) {
			System.out.println(student[i].getName() + "\t"
					+ student[i].getGrade());
		}

		Arrays.sort(student, new NameComparator());
		System.out
				.println("Order of students after sorting by student name is");

		for (int i = 0; i < student.length; i++) {
			System.out.println(student[i].getName() + "\t"
					+ student[i].getGrade());
		}
	}

}

Let’s explain the above code. We create an array of Students, three objects of type Student and then, we set the name and the final grade for each one of them. After that, we print to the output the array without sorting, then we sort the array (a) by grade and (b) by name, and finally, we print to the output the respective results. The sorting can be done by using the method sort(T[] a, Comparator c) of java.util.Arrays, which sorts the array of Students according to the order induced by the specified comparator (either NameComparator or GradeComparator, respectively).

If we run the above code, we will have the following results:

  • Output:
Order of students before sorting is: 
Nick	19
Helen	12
Ross	16
Order of students after sorting by student grade is
Nick	19
Ross	16
Helen	12
Order of students after sorting by student name is
Helen	12
Nick	19
Ross	16

2. Download the source code

This was an example of Comparator. Download the Eclipse project from here: ComparatorExample.zip

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close