Multi criteria sorting of a list of objects with Guava Ordering

前端 未结 3 885
[愿得一人]
[愿得一人] 2021-02-13 23:30

I have a class WHICH CANNOT implement comparable, but needs to be sorted based on 2 fields. How can I achieve this with Guava?

Let\'s say the class is:

c         


        
3条回答
  •  温柔的废话
    2021-02-13 23:55

    Java 8 provides methods on Comparator to concisely specify chained comparators. Together with the newly-introduced List.sort, you can do:

    lotsOfX.sort(
        Comparator.comparingInt(x -> stringValueSortFunction.apply(x.stringValue))
            .thenComparing(x -> x.dateValue, Comparator.reverseOrder()));
    

    This mutates the list, of course -- make a copy first if you want to leave the original list unchanged, or wrap the comparator in an Ordering and use immutableSortedCopy if you want an immutable copy.

提交回复
热议问题