用 Comparator 实现排序

时间:2021-12-10 02:50:42
Interface Comparator<T>
对任意类型集合对象进行整体排序,排序时将此接口的实现传递给Collections.sort方法或者Arrays.sort方法排序。

实现int compare(T o1, T o2);方法,返回正数,零,负数各代表大于,等于,小于。

import java.util.Comparator;

public class CaseTestStepComparator implements Comparator {
    @Override
    public int compare(Object o1, Object o2) {
        CaseTestStep c1 = (CaseTestStep) o1;
        CaseTestStep c2 = (CaseTestStep) o2;

        int result = 0;

        if (c1 != null && c1.getOrderId() != null && c2 != null
                && c2.getOrderId() != null)
            result = c1.getOrderId().compareTo(c2.getOrderId());
        else if ((c1 == null || c1.getOrderId() == null)
                && (c2 == null || c2.getOrderId() == null))
            result = 0;
        else if (c1 == null || c1.getOrderId() == null)
            result = -1;
        else if (c2 == null || c2.getOrderId() == null)
            result = 1;

        return result;
    }
}