How use Comparator to define a custom sort order

Suraj Batuwana
1 min readApr 19, 2023

If you want to develop a sorting a demo for Employee list. I am using data table to employee car list. Now I want to sort the list by defined employee ids. Here it is not sort by alphabetic order. I want to use my custom sorting order like employee id 100 , 99, 98, 200 etc.

For that I try to use Java/Spring boot Comparator and Comparable but it allows to sort in alphabetic order only.

@Component
@Slf4j
@RequiredArgsConstructor
public class EmployeeComparator implements Comparator<Employee> {

private final EmployeeProperties employeeProperties;

@Override
public int compare(final Employee e1, final Employee e2) {
return Integer.valueOf(
employeeProperties.getEmployeeOrder().indexOf(o1.getId()))
.compareTo(
Integer.valueOf(
employeeProperties.getEmployeeOrder().indexOf(o2.getId())));
}

}
@Data
@Configuration
@ConfigurationProperties(prefix = "employee")
public class EmployeeProperties {
private List<String> employeeOrder;
}
In applocation.properties
employee-order = 100 , 99, 98, 200
@Component
@Slf4j
@RequiredArgsConstructor
public class EmployeeService {
private final EmployeeComparator employeeComparator;public List<Employee> getEmployeeList() {
...
...
return employeeList.stream().sorted(employeeComparator).collect(Collectors.toList()) }}

Same technique can be used to sort define list for Strings

--

--

Suraj Batuwana

Technology Evangelist, Technical Blogger with multidisciplinary skills with experience in full spectrum of design, architecture and development