|
| 1 | +import java.time.LocalDate; |
| 2 | +import java.util.ArrayList; |
| 3 | +import java.util.Collections; |
| 4 | +import java.util.Comparator; |
| 5 | +import java.util.List; |
| 6 | + |
| 7 | +public class ComparatorExample { |
| 8 | + public static void main(String[] args) { |
| 9 | + List<Employee> employees = new ArrayList<>(); |
| 10 | + |
| 11 | + employees.add(new Employee(1010, "Rajeev", 100000.00, LocalDate.of(2010, 7, 10))); |
| 12 | + employees.add(new Employee(1004, "Chris", 95000.50, LocalDate.of(2017, 3, 19))); |
| 13 | + employees.add(new Employee(1015, "David", 134000.00, LocalDate.of(2017, 9, 28))); |
| 14 | + employees.add(new Employee(1009, "Steve", 100000.00, LocalDate.of(2016, 5, 18))); |
| 15 | + |
| 16 | + System.out.println("Employees : " + employees); |
| 17 | + |
| 18 | + // Sort employees by Name |
| 19 | + Collections.sort(employees, Comparator.comparing(Employee::getName)); |
| 20 | + System.out.println("\nEmployees (Sorted by Name) : " + employees); |
| 21 | + |
| 22 | + // Sort employees by Salary |
| 23 | + Collections.sort(employees, Comparator.comparingDouble(Employee::getSalary)); |
| 24 | + System.out.println("\nEmployees (Sorted by Salary) : " + employees); |
| 25 | + |
| 26 | + // Sort employees by JoiningDate |
| 27 | + Collections.sort(employees, Comparator.comparing(Employee::getJoiningDate)); |
| 28 | + System.out.println("\nEmployees (Sorted by JoiningDate) : " + employees); |
| 29 | + |
| 30 | + // Sort employees by descending order of Name |
| 31 | + Collections.sort(employees, Comparator.comparing(Employee::getName).reversed()); |
| 32 | + System.out.println("\nEmployees (Sorted by Name Descending Order) : " + employees); |
| 33 | + |
| 34 | + // Chaining multiple Comparators |
| 35 | + // Sort by Salary. If Salary is same then sort by Name |
| 36 | + Collections.sort(employees, Comparator.comparingDouble(Employee::getSalary).thenComparing(Employee::getName)); |
| 37 | + System.out.println("\nEmployees (Sorted by Salary and Id) : " + employees); |
| 38 | + } |
| 39 | +} |
0 commit comments