Search code examples
javalistlexicographic-ordering

How to sort a list by multiple fields in different orders (asc/desc) in Java?


I have an ArrayList in Java and each element in the list is an object with 3 fields (a, b and c). I should order by a in ascending order; if 2 elements have the same value for a, they should be ordered by b in descending order; finally, if 2 elements have the same value even for b, they should be ordered by c in ascending order.

I tried other solutions posted on stackoverflow that are based on Comparator, but I did not get to order in descending order.

Could anyone kindly help me? Many thanks!


Solution

  • Comparator.reversed() for descending order

        Comparator<Element> compar = Comparator.comparing(Element::getA)
                .thenComparing(Comparator.comparing(Element::getB).reversed())
                .thenComparing(Element::getC);
        yourArrayList.sort(compar);
    

    In addition to the reversed method I am exploiting the fact that thenComparing() is overloaded: one thenComparing() takes a Comparator as argument, which we need for reversing, the other just takes a method reference (or lambda) as argument (a Function in the declaration of thenComparing()).

    If either a, b or c is a primitive int, long or double remember to use comparingInt(), comparingLong(), comparingDouble(), thenComparingInt(), etc.