Posts

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 >