[英]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.