Multi criteria sorting of a list of objects with Guava Ordering

前端 未结 3 889
[愿得一人]
[愿得一人] 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.

    0 讨论(0)
  • 2021-02-14 00:15

    I suspect you want Ordering.compound. You could do it all in one statement, but I'd use:

    Ordering<X> primary = Ordering.natural().onResultOf(stringValueSortFunction);
    Ordering<X> secondary = Ordering.natural()
                                  .onResultOf(dateValueSortFunction)
                                  .reverse();
    Ordering<X> compound = primary.compound(secondary);
    
    List<X> sortedList = compound.immutableSortedCopy(lotsOfX);
    
    0 讨论(0)
  • 2021-02-14 00:15

    A less functional, but arguably cleaner, solution:

    new Ordering<X>() {
      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);
    
    0 讨论(0)
提交回复
热议问题