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?
To sort on multiple fields, we must first create simple comparators for each field on which we want to sort the stream items. Then we chain these Comparator instances in the desired order to give GROUP BY effect on complete sorting behavior.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With