根据元素的自然排序对列表进行排序

时间:2015-05-18 20:22:17

标签: java sorting comparator

我想要下面的降序排序类型:

这是升序排序:

public static <T extends Vm> void sortByCpuUtilization(List<T> vmList) {
    Collections.sort(vmList, new Comparator<T>() {

        @Override
        public int compare(T a, T b) throws ClassCastException {
            Double aUtilization = a.getTotalUtilizationOfCpuMips(CloudSim.clock());
            Double bUtilization = b.getTotalUtilizationOfCpuMips(CloudSim.clock());
            return bUtilization.compareTo(aUtilization);
        }
    });
}

2 个答案:

答案 0 :(得分:1)

比较a和b:

public static <T extends Vm> void sortByCpuUtilization(List<T> vmList) {
    Collections.sort(vmList, new Comparator<T>() {

        @Override
        public int compare(T a, T b) throws ClassCastException {
            Double aUtilization = a.getTotalUtilizationOfCpuMips(CloudSim.clock());
            Double bUtilization = b.getTotalUtilizationOfCpuMips(CloudSim.clock());
            return aUtilization.compareTo(bUtilization);
        }
    });
}

答案 1 :(得分:1)

有几种方法可以做到这一点。首先,您可以实现一个反向比较器:

public static <T extends Vm> void sortByCpuUtilizationDesc(List<T> vmList) {
    Collections.sort(vmList, new Comparator<T>() {

        @Override
        public int compare(T a, T b) throws ClassCastException {
            Double aUtilization = a.getTotalUtilizationOfCpuMips(CloudSim.clock());
            Double bUtilization = b.getTotalUtilizationOfCpuMips(CloudSim.clock());
            return aUtilization.compareTo(bUtilization); // Note this is reversed
        }
    });
}

但更优雅的是,您可以使用Collections.reverseOrder

public static <T extends Vm> void sortByCpuUtilizationDesc(List<T> vmList) {
    // Same comparator as before, should be extracted to a named class.
    Collections.sort(vmList, Collections.reverseOrder(new Comparator<T>() {

        @Override
        public int compare(T a, T b) throws ClassCastException {
            Double aUtilization = a.getTotalUtilizationOfCpuMips(CloudSim.clock());
            Double bUtilization = b.getTotalUtilizationOfCpuMips(CloudSim.clock());
            return aUtilization.compareTo(bUtilization); // Note this is reversed
        }
    }));
}