How to compare objects by multiple fields

后端 未结 22 2550
暖寄归人
暖寄归人 2020-11-22 00:43

Assume you have some objects which have several fields they can be compared by:

public class Person {

    private String firstName;
    private String lastN         


        
22条回答
  •  爱一瞬间的悲伤
    2020-11-22 01:22

    Following blog given good chained Comparator example

    http://www.codejava.net/java-core/collections/sorting-a-list-by-multiple-attributes-example

    import java.util.Arrays;
    import java.util.Comparator;
    import java.util.List;
    
    /**
     * This is a chained comparator that is used to sort a list by multiple
     * attributes by chaining a sequence of comparators of individual fields
     * together.
     *
     */
    public class EmployeeChainedComparator implements Comparator {
    
        private List> listComparators;
    
        @SafeVarargs
        public EmployeeChainedComparator(Comparator... comparators) {
            this.listComparators = Arrays.asList(comparators);
        }
    
        @Override
        public int compare(Employee emp1, Employee emp2) {
            for (Comparator comparator : listComparators) {
                int result = comparator.compare(emp1, emp2);
                if (result != 0) {
                    return result;
                }
            }
            return 0;
        }
    }
    

    Calling Comparator:

    Collections.sort(listEmployees, new EmployeeChainedComparator(
                    new EmployeeJobTitleComparator(),
                    new EmployeeAgeComparator(),
                    new EmployeeSalaryComparator())
            );
    

提交回复
热议问题