Java stream sort 2 variables ascending/desending

放肆的年华 提交于 2019-11-27 12:59:59

问题


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());

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

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?


回答1:


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());


来源:https://stackoverflow.com/questions/30382453/java-stream-sort-2-variables-ascending-desending

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!