HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Collections Framework / Java Comparator interface example

Java Comparator interface example

Java Comparator interface used to sort a array or list of objects based on custom order. Custom ordering of elements is imposed by implementing Comparator.compare() method in the objects.

1. Java Comparator interface

Java Comparator interface imposes a total ordering on the objects which may not have a natural ordering.

For example, for a list of elpmoyees object, the natural order may be order by employee id. But in real life applications, we may want to sort the list of employees by their first name, date of birth or simply any other such criteria. In such conditions, we need to use Comparator interface.

We can use Comparator interface in following situations.

  1. Sort the array or list of objects, but NOT in natural order.
  2. Sort the array or list of objects where we can not modify the object’s source code to implement Comparable interface.
  3. Sort same list or array of objects on different fields.
  4. Using group by sort on list or array of objects on different fields.

1.1. Comparator.compare()

To enable total ordering on objects, we need to create class which implements Comparator interface. Then we need to override it’s compare(T o1, T o2) method.

It compares its two arguments for order. It returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

The implementor must also ensure that the relation is transitive: ((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0.

import java.time.LocalDate;

public class Employee implements Serializable {

    private static final long serialVersionUID = 1L;

    private Long id;
    private String name;
    private LocalDate dob;

    //Getters and Setters

    @Override
    public String toString() {
        return "Employee [id=" + id + ", name=" + name + ", dob=" + dob + "]";
    }
}

For above class, an order by employee name can be imposed by creating Comparator like below.

import java.util.Comparator;

public class NameSorter implements Comparator<Employee>
{
    @Override
    public int compare(Employee e1, Employee e2) {
        return e1.getName().compareToIgnoreCase( e2.getName() );
    }
}

1.2. Collections.sort() and Arrays.sort()

  1. Use Collections.sort(list, Comparator) method sort a list of objects in order imposed by provided comparator instance.
  2. Use Arrays.sort(array, Comparator) method sort an array of objects in order imposed by provided comparator instance.

1.3. Collections.comparing()

This utility method accepts a function that extracts a sort key for the class. This is essentially a field on which the class objects will be sorted.

//Order by name
Comparator.comparing(Employee::getName);

//Order by name in reverse order
Comparator.comparing(Employee::getName).reversed();

//Order by id field
Comparator.comparing(Employee::getId);

//Order by employee age
Comparator.comparing(Employee::getDate);

1.4. Collections.thenComparing()

This utility method is used for group by sort. Using this method, we can chain multiple comparators to sort the list or array of objects on multiple fields.

It is very similar to SQL GROUP BY clause to order rows on different fields.

//Order by name and then by age
Comparator.comparing(Employee::getName)
			.thenComparing(Employee::getDob);

//Order by name -> date of birth -> id 
Comparator.comparing(Employee::getName)
			.thenComparing(Employee::getDob)
			.thenComparing(Employee::getId);

Using above syntax, we can create virtually any sorting logic.

1.5. Collections.reverseOrder()

This utility method returns a comparator that imposes the reverse of the natural ordering or total ordering on a collection of objects that implement the Comparable interface.

//Reverse of natural order as specified in 
//Comparable interface's compareTo() method 

Comparator.reversed();

//Reverse of order by name

Comparator.comparing(Employee::getName).reversed();

2. Java Comparator example

2.1. Sort list of objects

Java example to sort a list of employees by name using Comparator.

ArrayList<Employee> list = new ArrayList<>();
        
list.add(new Employee(22l, "Lokesh", LocalDate.now()));
list.add(new Employee(30l, "Bob", LocalDate.now()));
list.add(new Employee(18l, "Alex", LocalDate.now()));
list.add(new Employee(5l, "David", LocalDate.now()));
list.add(new Employee(600l, "Charles", LocalDate.now()));

//Sort in reverse natural order
Collections.sort(list, new NameSorter());

System.out.println(list);

Program Output.

[
	Employee [id=18, name=Alex, dob=2018-10-30], 
	Employee [id=30, name=Bob, dob=2018-10-30], 
	Employee [id=600, name=Charles, dob=2018-10-30], 
	Employee [id=5, name=David, dob=2018-10-30], 
	Employee [id=22, name=Lokesh, dob=2018-10-30]
]

2.2. Sort list of objects in reverse order

Java example to sort a list of employees by name using Comparator in reverse order.

ArrayList<Employee> list = new ArrayList<>();
        
list.add(new Employee(22l, "Lokesh", LocalDate.now()));
list.add(new Employee(30l, "Bob", LocalDate.now()));
list.add(new Employee(18l, "Alex", LocalDate.now()));
list.add(new Employee(5l, "David", LocalDate.now()));
list.add(new Employee(600l, "Charles", LocalDate.now()));

Collections.sort(list, Comparator.comparing( Employee::getName ).reversed());

System.out.println(list);

Program Output.

[
	Employee [id=22, name=Lokesh, dob=2018-10-30], 
	Employee [id=5, name=David, dob=2018-10-30], 
	Employee [id=600, name=Charles, dob=2018-10-30], 
	Employee [id=30, name=Bob, dob=2018-10-30], 
	Employee [id=18, name=Alex, dob=2018-10-30]
]

2.3. Group by sorting list of objects in multiple fields

Java example to sort a list of employees on multiple fields i.e. field by field.

ArrayList<Employee> list = new ArrayList<>();
        
list.add(new Employee(22l, "Lokesh", LocalDate.now()));
list.add(new Employee(30l, "Lokesh", LocalDate.now()));
list.add(new Employee(18l, "Alex", LocalDate.now()));
list.add(new Employee(5l, "Lokesh", LocalDate.now()));
list.add(new Employee(600l, "Charles", LocalDate.now()));

Comparator<Employee> groupByComparator = Comparator.comparing(Employee::getName)
                                        .thenComparing(Employee::getDob)
                                        .thenComparing(Employee::getId);

Collections.sort(list, groupByComparator);

System.out.println(list);

Program Output.

[
	Employee [id=18, name=Alex, dob=2018-10-30], 
	Employee [id=600, name=Charles, dob=2018-10-30], 
	Employee [id=5, name=Lokesh, dob=2018-10-30], 
	Employee [id=22, name=Lokesh, dob=2018-10-30], 
	Employee [id=30, name=Lokesh, dob=2018-10-30]]

3. Conclusion

In this tutorial, we learned about Comparator interface of Java collection framework. It helps in imposing a total order on objects without any change to sourcecode of that class.

We learned to sort list and array of objects. We learned how to sort employee objects in java using Comparator interface i.e. java comparator example multiple fields.

Drop me your questions in comments section.

Happy Learning !!

References:

Comparator Interface Java Docs

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

Java Collections

  • Collections Framework
  • Array
  • ArrayList
  • LinkedList
  • HashMap
  • Hashtable
  • LinkedHashMap
  • TreeMap
  • HashSet
  • LinkedHashSet
  • TreeSet
  • Comparable
  • Comparator
  • Iterator
  • ListIterator
  • Spliterator
  • PriorityQueue
  • PriorityBlockingQueue
  • ArrayBlockingQueue
  • LinkedTransferQueue
  • CopyOnWriteArrayList
  • CopyOnWriteArraySet
  • Collection Sorting
  • Interview Questions

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces