Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java stream sort 2 variables ascending/desending

Tags:

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?

like image 374
Bruce Avatar asked May 21 '15 19:05

Bruce


People also ask

How do you Multi sort in Java?

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.


1 Answers

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()); 
like image 80
assylias Avatar answered Sep 25 '22 23:09

assylias