Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
comparator
interface
collection

What is the Java Comparator interface?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The Java Comparator interface is used to provide a custom sorting order for a data structure; this is usually done with user-defined types. The Comparator interface is passed on to a sorting function (i.e., Collections.sort()) to temporarily alter the sorting criteria of a collection:

compare(obj1, obj2)

It is necessary to override this method when using the Comparator interface; the method should return:

  • a negative integer, if obj1 is less than obj2.
  • zero, if obj1 is equal to obj2.
  • a positive integer, if obj1 is greater than obj2.
svg viewer
Declaring a Comparator and passing it to a sorting function.

Code

In the following code, an ArrayList of type Person is sorted on the basis of id using a Comparator:

ComparatorShot.java
Person.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class ComparatorShot {
	
	public static void main(String[] args) {
		ArrayList<Person> arr = new ArrayList<>();
		arr.add(new Person(1, "John"));
		arr.add(new Person(5, "Terry"));
		arr.add(new Person(0, "Lukaku"));
		arr.add(new Person(2, "Pablo"));
		
		// Passing Comparator anonymously:
		Collections.sort(arr, new Comparator<Person>() {
			@Override
			public int compare(Person p1, Person p2) {
				// Sorting by IDs:
				
				if(p1.id < p2.id)
					return -1;
				else if(p1.id > p2.id)
					return 1;
				else
					return 0;
			}
		});
		
		// Displaying sorted array:
		arr.forEach(System.out::println);
	}
}

RELATED TAGS

java
comparator
interface
collection
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring