How to define custom Comparators (3 ways)?

Custom Comparators are used to sort the user defined objects. Define custom comparator gives you flexibility to sort the objects in multiple ways, for example sort strings by alphabetical order or by their lengths. If you have a People class with first name and last name, you can sort by their first name, last name or both. Know how to use the comparators provided by the language are vital to work efficiently.

But the syntax of using comparators can be very confusing. Here we show how to define Comparator in Java, JavaScript and Python. We also show three ways to define comparators: lambda, function or external class, The examples also demonstrate how to call them after you define them.


1. Define Comparator as lambda

Lambda is the most easy way to do. You can simply put lambda in the place where requires Comparator. In Java, the syntax to compare two object is (a,b) -> a.id – b.id; In JavaScript, the syntax is (a,b) => a.id – b.id; In Python, the syntax is key = lambda x: x.id . Lambda is preferred when the comparison is simple .

If you have more complicated comparison involving multiple lines of code, lambda is not that convenient for Java and JavaScript. Python is easier by simply listing all the attributes for comparison.

Java

JavaScript

Python


2. Define comparator as function

In JavaScript and Python, this is to define the comparator as function and pass it in as the parameter for sort() method. The function can be inline. But more often, we define the function first. Then use the function name as the input parameter.

Java is little different. We declare a static variable of Comparator and call new Comparator(), followed by the implementation of compare() method. This is similar to JavaScript when assigning a function to a variable. This variable will be used as input parameter for the sort() method.

Java

JavaScript

Python


3. Define Comparator as class

This is for Java only. We define Comparator as a separate class. The class implements Comparator interface. Inside the class, implement compare() method to compare two objects, and return an integer. Since it is class, we have to new class which will be the input parameter for the sort() method.

Java


Java coding interview pocket book (2nd edition)
Java coding interview questions series (YouTube)

Comments are closed