Java stream sort 2 variables ascending/desending

Bruce picture Bruce · May 21, 2015 · Viewed 15.7k times · Source

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?

Answer

assylias picture assylias · May 21, 2015

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