Java Sort a List of Objects using Comparator
In this article, I have shown a way to sort a list of Employee object based on a specific field and the sorting order using Comparator. The code snippet shows that the sorting criteria are configurable, eliminating the need to add an if/else block when a new criterion is introduced.
Create two enums SortingCriteria and SortingOrder.
enum SortingCriteria { NAME, AGE } enum SortingOrder { ASC, DESC }
Now create a Map to store SortingCriteria mapping with the ascending order (default) Comparators e.g., Name comparator, Age comparator, etc.
static Map<SortingCriteria, Comparator<Employee>> comparatorMap = Map.of(NAME, Comparator.comparing(Employee::getName), AGE, Comparator.comparing(Employee::getAge));
Create a method to accept the SortingCriteria and the SortingOrder as user input and return the sorted employees. Here we are assuming that a List of employees is already available.
static List<Employee> sort(SortingCriteria criteria, SortingOrder order) { List<Employee> employees = new ArrayList<>(); // consider populated //If order is DESC then we take reversed() comparator Comparator<Employee> employeeComparator = order == ASC ? comparatorMap.get(criteria) : comparatorMap.get(criteria).reversed(); employees.sort(employeeComparator); return employees; }
Conclusion: The benefit of this approach is that to enable sorting for a new criterion, let's say ID, we just need to add ID in SortingCriteria and add a new mapping in the comparatorMap. This way, the core sorting logic remains unchanged.
Comments
Post a Comment