简体   繁体   English

ASC 和 DESC 顺序的自定义比较器实现

[英]Custom Comparator implementation for both ASC and DESC order

I'm trying to find a way to define an unique implementation of java.util.Comparator usable for both ascending and descending ordering purpose.我试图找到一种方法来定义java.util.Comparator的独特实现,可用于升序和降序目的。

I have defined a class Golf.java that represents Volkswagen's car.我已经定义了一个代表大众汽车的类Golf.java I also defined a Comparator that order Golf instances by horses power ( int variable).我还定义了一个 Comparator,它按马力( int变量)对Golf实例进行排序。 I was wondering if it's possible to use the same comparator for both ascending and descending ordering.我想知道是否可以对升序和降序使用相同的比较器。

GolfHorsePowerComparator.java 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;
    }

}

Given a list of Golf how could I sort them ascending or descending using the same java.util.Comparator implementation?给定一个Golf列表,我如何使用相同的java.util.Comparator实现对它们进行升序或降序排序?

You can use Collections::reverseOrder to sort in desc order.您可以使用Collections::reverseOrder按降序排序。 Eg:例如:

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

Yes, look at documentation .是的,查看文档 Comparator has a reversed method. Comparator有一个reversed方法。 You can simply do this:你可以简单地这样做:

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

The first one sorts ascending, the second - descending.第一个排序升序,第二个 - 降序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java 自定义比较器实现 - Java custom Comparator implementation 除了Asc / Desc,还有其他使用Mysql Order By的方法吗? - Besides Asc/Desc, Any other way to use Mysql Order By? 无法在 postgresql、JPQL 的“case when”内按 ASC 或 DESC 订购 - Couldn't Order by ASC or DESC inside "case when" in postgresql, JPQL 在JPA Query中,我可以通过属性和DESC / ASC顺序传递顺序作为方法签名中的参数吗? - In JPA Query, can I pass the order by property and DESC/ASC order as parameters in the method signature? 需要基于单个对象值对列表使用集合排序对ASC和DESC进行排序 - Need Sorting on both ASC and DESC using collection sort for List based on single object value 是否有具有固定容量和自定义比较器的 PriorityQueue 实现? - Is there a PriorityQueue implementation with fixed capacity and custom comparator? 比较器实施 - Comparator Implementation 如何根据输入值和 Asc/Desc 作为用户输入执行自定义排序 -Java - How to perform a custom sort based on input values and Asc/Desc as user Input -Java 使用自定义比较器(如Excel坐标顺序)订购TreeMap - Order a TreeMap with custom comparator like Excel coordinate order ($ propertyname,)+ [asc | desc]是什么意思? - What does `($propertyname,)+[asc|desc]?` actually means?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM