Search code examples
javasortingjava-8comparatorjava-stream

Java stream sort 2 variables ascending/desending


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?


Solution

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