SEARCH BY

All

  • All
  • Java8
  • Spring

Using Comparator to sort elements of List

Post a Comment
Here in this example we will see detailed explanation about how to sort elements of List of Employees by using Comparator interface.
List can be sorted based on Sort Key, we can sort elements based on Single Sort Key or Multiple Sort Keys.

There are two important methods called as comparring() and thenComparring() to perform Single Sort key based sorting and/or multiple sort keys based sorting.

Note: Here this is the example based on Java8 ann/or higher versions of java8

Steps to sort :

Sorting by Single Sort Key

First we need to create Comparator object with comparring() and then we need to call sort() method on Collections or collection object

Comparator<Employee> sortingBYFname=Comparator.comparring(Employee:getFname);

Collections.sort(empList,sortingByFname); // This will return a new empList with sorted employees by First Name
In the above example fname is a sort key, getFname is a getter method to get Fname from employee. Here we have used :: for invoking methods directly.

Sorting by Multiple Sort Keys ( in this example that is by empId and Employee First Name )

 Now we will see how to sort elements by multiple sort keys by using thenComaparring() method.
// creating Comparator with multiple sort keys where as id and fname
Comparator<Employee> c_emp_by_id_fname=Comparator.comparing(Employee::getEmpId).thenComparing(Employee::getFname);
// here we are using list.sort(comparator_obj) for sorting
empListNew.sort(c_emp_by_id_fname);
jaya
I love software designing, coding, writing and teaching...

Share this article

Related Posts

Post a Comment

Place your code in <em> </em> tags to send in comments | Do not add hyper links in commnet

Close

Subscribe our newsletter for the latest articles directly into your email inbox