
[英]Is there a way to sort the rank in Mpi by ascending and descending order
[英]Sort collection descending but equals values in ascending way
当我有一个不等于firstValue
和secondValue
时,我试图对一个集合进行排序,我只是返回它的比较结果,它会以升序方式对其进行排序,但是当这些值等于时,我也想按名称以升序方式对其进行排序。 一切正常,但是当我必须按firstValue
和secondValue
以降序方式对集合进行排序时,我遇到了一个问题。 当firstValue
和secondValue
相等时,我仍想按名称以升序方式对其进行排序,但使用相反的顺序,它将按名称以降序方式排序。
这里是升序排序的代码:
prices.setPriceModels(prices.getPriceModels().stream().sorted((o1, o2) -> {
int compareResult = o1.getPrice().compareTo(o2.getPrice());
if (compareResult == 0) {
String firstCompareName = Optional.ofNullable(o1.getName()).orElse(StringUtils.EMPTY);
String secondCompareName = Optional.ofNullable(o2.getName()).orElse(StringUtils.EMPTY);
return firstCompareName.compareTo(secondCompareName);
}
return compareResult;
}).collect(Collectors.toList()));
主要目标是以降序方式对整个集合进行排序,如果某些值相等,则这些值应按名称以升序方式排序。 是否可以使用 stream API 的reverseOrder()
来实现? 或者有什么更好的解决方案?
这个比较器怎么样?
prices.getPriceModels().stream().sorted(Comparator.comparing(PriceModel::getPrice).reversed() // using PriceModel's Price to sort in descending order
// for PriceModels with equal Prices, using PriceModel' name to sort in ascending order (with null values of name's treated to be less than any non-null value)
.thenComparing(PriceModel::getName, Comparator.nullsFirst(Comparator.naturalOrder())))
.collect(Collectors.toList())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.