Comparator based on different nullable fields of an object

社会主义新天地 提交于 2019-12-06 01:11:50

If either of the titles is null, then the two Employees will evaluate as equals, even if one of them is not null. That's not what you want. You want all null titles to be equal to each other, but not non-null values.

Replace your compare method with this:

public int compare(Employee emp1, Employee emp2) {
    if(emp1.getJobTitle() == null && emp2.getJobTitle() == null){
        return 0;
    }
    if(emp1.getJobTitle() == null) return 1;
    if(emp2.getJobTitle() == null) return -1;
    return emp1.getJobTitle().compareTo(emp2.getJobTitle());
}

And you should get the results you expect.

Tunaki

Since you're using Java 8, you can use the built-in comparator facilities instead of creating your own comparators. Comparing the job title and then the name can easily be done with

Comparator<Employee> comparator =
     Comparator.comparing(Employee::getJobTitle).thenComparing(Employee:getName);

How to handle null values is also built-in with the nullsLast and nullsFirst methods. Those methods wrap an existing comparator into a null safe comparator, putting null values either at the end or at the start.

As such, you can have:

import static java.util.Comparator.comparing;
import static java.util.Comparator.naturalOrder;
import static java.util.Comparator.nullsLast;

// ...

Comparator<Employee> comparator = 
    comparing(Employee::getJobTitle, nullsLast(naturalOrder())).thenComparing(Employee::getName);

Collections.sort(listEmployees, comparator);

The comparator is created by comparing the job titles with a null safe comparator putting null values last (see also). For equal titles, it is thenComparing the name of the employees.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!