Java流排序2变量升序/取消发送 [英] Java stream sort 2 variables ascending/desending

查看:264
本文介绍了Java流排序2变量升序/取消发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对seq1升序和seq2降序进行排序,所以我这样做:

I want to sort seq1 ascending and seq2 descending so I do this:

list = list.stream().sorted(comparing(AClass::getSeq1).thenComparing(        
   AClass::getSeq2).reversed()).collect(toList());

但是结果出来了,因为seq1和seq2都按降序排序。

But the result come out as both seq1 and seq2 are sorted in descending order.

我可以这样做以使seq1升序和seq2降序:

I can do this to make seq1 ascending and seq2 descending:

sorted(comparing(AClass::getSeq1)
   .reversed().thenComparing(AClass::getSeq2).reversed()

这样做的确切方法是什么?

What is really the correct way to do this?

推荐答案

在你的第一个例子中, reverse 应用于整个比较器,比较seq1然后seq2按升序。

In your first example, reversed is applied to the whole comparator which compares seq1 then seq2 in ascending order.

你需要的是仅反转第二个比较,可以完成,例如,使用:

What you need is to reverse the second comparison only, which can be done, for example, with:

import static java.util.Collections.reverseOrder;
import static java.util.Comparator.comparing;

list = list.stream().sorted(
                        comparing(AClass::getSeq1)
                       .thenComparing(reverseOrder(comparing(AClass::getSeq2))))
                       .collect(toList());


//or you could also write:

list = list.stream().sorted(
                        comparing(AClass::getSeq1)
                       .thenComparing(comparing(AClass::getSeq2).reversed()))
                       .collect(toList());

这篇关于Java流排序2变量升序/取消发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆