【问题标题】:Custom Comparator implementation for both ASC and DESC orderASC 和 DESC 订单的自定义比较器实现
【发布时间】:2019-08-28 21:11:36
【问题描述】:

我正在尝试找到一种方法来定义java.util.Comparator 的唯一实现,可用于升序和降序。

我定义了一个代表大众汽车的类Golf.java。我还定义了一个比较器,它按马力(int 变量)对 Golf 实例进行排序。我想知道是否可以对升序和降序使用相同的比较器。

GolfHorsePowerComparator.java

package test2.comparator;

import test2.dto.Golf;
import java.util.Comparator;

public class GolfHorsePowerComparator implements Comparator<Golf> {

    @Override
    public int compare(Golf a, Golf b) {
        return a.getHorsePower() > b.getHorsePower() ? 1 : a.getHorsePower() == b.getHorsePower() ? 0 : -1;
    }

}

鉴于Golf 的列表,我如何使用相同的java.util.Comparator 实现对它们进行升序或降序排序?

【问题讨论】:

    标签: java algorithm sorting collections comparator


    【解决方案1】:

    您可以使用Collections::reverseOrder 按降序排序。例如:

    GolfHorsePowerComparator golfHorsePowerComparator = new GolfHorsePowerComparator();
    Collections.sort(golfList, Collections.reverseOrder(golfHorsePowerComparator));
    

    【讨论】:

    • 谢谢!所以最好的做法是在项目中编写自定义Comparator 总是升序或降序,然后使用Collections.reverseOrder(customComparator) 方法来恢复排序,对吧?
    • @Gozus19 是的,这正是在 api 中引入 reverseOrder 的原因。
    【解决方案2】:

    是的,看看documentationComparator 有一个 reversed 方法。你可以这样做:

    list.stream().sorted(comparator).collect(Collectors.toList());
    list.stream().sorted(comparator.reversed()).collect(Collectors.toList());
    

    第一个升序,第二个降序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-17
      • 2015-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-29
      相关资源
      最近更新 更多