Sort with Java Comparator

Java Comparators are used to sort the user defined objects. It gives you flexibility to sort the objects in multiple ways. For example you can sort strings by alphabetical order, or by their lengths. If you have a People class with first name, last name and age, you can sort by the name, age or combinations. The syntax of custom comparator in Java are confusing. Applying the examples provided here as template will save you time.

1. Define Java comparator as class

After you define the custom class, you 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, you have to new class which will be the input parameter for the sort() method.

2. Define comparator as static method

This is a variation of defining comparator in Java. You declare a static method of Comparator and call new Comparator(), followed by the implementation of compare() method. Then you can sort with the method as the input parameter.

Sort countries by Id:
[(1 Kenya), (2 Mexico), (2 America), (3 Spain), (4 Saudi arabia)]

Sort countries by name:
[(2 America), (1 Kenya), (2 Mexico), (4 Saudi arabia), (3 Spain)]

Sort countries by id and name:
[(1 Kenya), (2 America), (2 Mexico), (3 Spain), (4 Saudi arabia)]

Sort with lambda comparator
Coding questions series (YouTube)

Comments are closed