Java Comparator

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

Sign in Get started

TyAnthoney Morrell JAVA S P RING MY S IT E

You have 2 free stories left this month. Sign up and get an extra one for free.

Java Comparator
TyAnthoney Morrell Follow
Mar 20, 2019 · 3 min read

Photo by Maximilian Weisbecker on Unsplash

Some of the time in Java it is desirable to sort classes that you have
written yourself. When this is necessary we can use the Java Comparator
Interface to implement our custom sorts.

When implementing the Comparator Interface you must override the


abstract method compare.

public int compare(Object a, Object b);

This is the method that will hold the code you wish to be executed in your
custom sorting.

Let’s assume that we are writing an application that will contain lists of
customers and that you would need to be sorting these customers for
various reasons. We can start out with a Customer class like the one
below:

public class Customer {

private Integer customerID;


private String fName, lName;

// getters and setters omitted

We can write three different classes for sorting this data: the first would
be for the employee ID;

public class CustomerIDSort implements Comparator<Customer> {

@Override
public int compare(Customer a, Customer b) {

return a.getCustomerID().compareTo(b.getCustomerID());

the second would be for the last name;

public class LastNameSort implements Comparator<Customer> {

@Override
public int compare(Customer a, Customer b) {

return a.getlName().compareTo(b.getlName());

and the third for the first name.

public class FirstNameSort implements Comparator<Customer> {

@Override
public int compare(Customer a, Customer b) {

return a.getfName().compareTo(b.getfName());

We can use these classes to sort a list using Collections.sort like in the
main method below

public static void main(String[] args) {

List<Customer> customers = new ArrayList<>();

customers.add(new Customer(4, "Steve", "Pink"));


customers.add(new Customer(3, "Tim", "Orange"));
customers.add(new Customer(1, "Edward", "Blue"));
customers.add(new Customer(9, "Harvey", "White"));
customers.add(new Customer(2, "Quentin", "Brown"));
customers.add(new Customer(12, "Michael", "Blonde"));

System.out.println("Before sorting");

for (Customer customer : customers) {

System.out.println(customer.toString());

// sort by cutomer id
Collections.sort(customers, new CustomerIDSort());

System.out.println("\nSorted by CustomerID");

for (Customer customer : customers) {

System.out.println(customer.toString());

// sort by last name


Collections.sort(customers, new LastNameSort());

System.out.println("\nSorted by last name");

for (Customer customer : customers) {

System.out.println(customer.toString());

// sort by first name


Collections.sort(customers, new FirstNameSort());

System.out.println("\nSorted by first name");

for (Customer customer : customers) {

System.out.println(customer.toString());

Output

Before sorting
Customer{customerID=4, fName=Steve, lName=Pink}
Customer{customerID=3, fName=Tim, lName=Orange}
Customer{customerID=1, fName=Edward, lName=Blue}
Customer{customerID=9, fName=Harvey, lName=White}
Customer{customerID=2, fName=Quentin, lName=Brown}
Customer{customerID=12, fName=Michael, lName=Blonde}

Sorted by CustomerID
Customer{customerID=1, fName=Edward, lName=Blue}
Customer{customerID=2, fName=Quentin, lName=Brown}
Customer{customerID=3, fName=Tim, lName=Orange}
Customer{customerID=4, fName=Steve, lName=Pink}
Customer{customerID=9, fName=Harvey, lName=White}
Customer{customerID=12, fName=Michael, lName=Blonde}

Sorted by last name


Customer{customerID=12, fName=Michael, lName=Blonde}
Customer{customerID=1, fName=Edward, lName=Blue}
Customer{customerID=2, fName=Quentin, lName=Brown}
Customer{customerID=3, fName=Tim, lName=Orange}
Customer{customerID=4, fName=Steve, lName=Pink}
Customer{customerID=9, fName=Harvey, lName=White}

Sorted by first name


Customer{customerID=1, fName=Edward, lName=Blue}
Customer{customerID=9, fName=Harvey, lName=White}
Customer{customerID=12, fName=Michael, lName=Blonde}
Customer{customerID=2, fName=Quentin, lName=Brown}
Customer{customerID=4, fName=Steve, lName=Pink}
Customer{customerID=3, fName=Tim, lName=Orange}

If you are using Java 8 you can actually sort the above list or any other
list for that matter using a lambda expression instead of a class. Here is
how our main method would look if we were to use lamda expressions.

public static void main(String[] args) {

List<Customer> customers = new ArrayList<>();

customers.add(new Customer(4, "Steve", "Pink"));


customers.add(new Customer(3, "Tim", "Orange"));
customers.add(new Customer(1, "Edward", "Blue"));
customers.add(new Customer(9, "Harvey", "White"));
customers.add(new Customer(2, "Quentin", "Brown"));
customers.add(new Customer(12, "Michael", "Blonde"));

System.out.println("Before sorting");

for (Customer customer : customers) {

System.out.println(customer.toString());

// sort by cutomer id
Collections.sort(customers, (Customer a, Customer b) -> {

return a.getCustomerID().compareTo(b.getCustomerID());

});

System.out.println("\nSorted by CustomerID");

for (Customer customer : customers) {

System.out.println(customer.toString());

// sort by last name


Collections.sort(customers, (Customer a, Customer b) -> {

return a.getlName().compareTo(b.getlName());

});

System.out.println("\nSorted by last name");

for (Customer customer : customers) {

System.out.println(customer.toString());

// sort by first name


Collections.sort(customers, (Customer a, Customer b) -> {

return a.getfName().compareTo(b.getfName());

});

System.out.println("\nSorted by first name");

for (Customer customer : customers) {

System.out.println(customer.toString());

The output is the same

Before sorting
Customer{customerID=4, fName=Steve, lName=Pink}
Customer{customerID=3, fName=Tim, lName=Orange}
Customer{customerID=1, fName=Edward, lName=Blue}
Customer{customerID=9, fName=Harvey, lName=White}
Customer{customerID=2, fName=Quentin, lName=Brown}
Customer{customerID=12, fName=Michael, lName=Blonde}

Sorted by CustomerID
Customer{customerID=1, fName=Edward, lName=Blue}
Customer{customerID=2, fName=Quentin, lName=Brown}
Customer{customerID=3, fName=Tim, lName=Orange}
Customer{customerID=4, fName=Steve, lName=Pink}
Customer{customerID=9, fName=Harvey, lName=White}
Customer{customerID=12, fName=Michael, lName=Blonde}

Sorted by last name


Customer{customerID=12, fName=Michael, lName=Blonde}
Customer{customerID=1, fName=Edward, lName=Blue}
Customer{customerID=2, fName=Quentin, lName=Brown}
Customer{customerID=3, fName=Tim, lName=Orange}
Customer{customerID=4, fName=Steve, lName=Pink}
Customer{customerID=9, fName=Harvey, lName=White}

Sorted by first name


Customer{customerID=1, fName=Edward, lName=Blue}
Customer{customerID=9, fName=Harvey, lName=White}
Customer{customerID=12, fName=Michael, lName=Blonde}
Customer{customerID=2, fName=Quentin, lName=Brown}
Customer{customerID=4, fName=Steve, lName=Pink}
Customer{customerID=3, fName=Tim, lName=Orange}

That is it. We can now use what we have learned to write useful compare
methods to sort any type of class that we can think of. I hope this brief
summary of the Comparator Interface was helpful and should you like to
view the source code for this tutorial it is available on GitHub.

Java Java8

27 claps 3 responses

WRIT T EN BY
TyAnthoney Morrell Follow

TyAnthoney Morrell Follow

I am a Java developer, a family man, and an all around easy


going guy.. I have created this blog primarily as a shortcut to
the things I have and will learn in my professional life.

More From Medium

6 Stages of Learning a AWS Elastic Beanstalk Making Rust Projects Regex tutorial — A quick
New Programming infrastructure in code with Cargo cheatsheet by examples
Language with Terraform James Bowen Jonny Fox in Factory Mind
Jun Wu in Better Programming Andrey in Seamless Cloud

How to Use a PostGIS Windows Containers on Partial Updates (PATCH) Why is Free Pascal
Geometry With Peewee Kubernetes in Spring Boot better than PHP?
Oren Cohen Tyler Finethy in Better Henrick Kakutalwa Jakub Groncki in T he Startup
Programming

Discover Medium Make Medium yours Become a member


Welcome to a place where words matter. On Medium, Follow all the topics you care about, and we’ll deliver the Get unlimited access to the best stories on Medium — and
smart voices and original ideas take center stage - with no best stories for you to your homepage and inbox. Explore support writers while you’re at it. Just $5/month. Upgrade
ads in sight. Watch

About Help Legal

You might also like