Multi criteria sorting of a list of objects with Guava Ordering

前端 未结 3 887
[愿得一人]
[愿得一人] 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-14 00:15

    A less functional, but arguably cleaner, solution:

    new Ordering() {
      public int compare(X x1, X x2) {
        return ComparisonChain.start()
          .compare(x1.stringValue, x2.stringValue)
          .compare(x2.dateValue, x1.dateValue) // flipped for reverse order
          .result();
      }
    }.immutableSortedCopy(listOfXs);
    

提交回复
热议问题