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 :
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 objectComparator<Employee> sortingBYFname=Comparator.comparring(Employee:getFname); Collections.sort(empList,sortingByFname); // This will return a new empList with sorted employees by First NameIn 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);
Post a Comment
Post a Comment