Java Comparator using .reverseOrder() but with an inner class

后端 未结 4 1713
借酒劲吻你
借酒劲吻你 2021-02-05 03:42

I am creating a simple program to learn about the Java Comparator class. I have sorted an Arraylist into order but now I want to sort the list in descending order b

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-05 04:05

    One way to implement an reverse order comparator is to implement an Compartor-Delegate that invert the comparator result (by changing the order).

    public class ReverseOrder implements Comparator {
      private Comparator delegate;
      public ReverseOrder(Comparator delegate){
        this.delegate = delegate;
      }
    
      public int compare(T a, T b) {
        //reverse order of a and b!!!
        return this.delegate.compare(b,a);
      }
    }
    

    So the only thing you need to do is to use this delegate. For example:

      Comparator myComparator = new myComparator();
      List list = ...;
      List reverse = new ArrayList(list);
    
      //acceding
      Collections.sort(list, myComparator);
    
      //descending
      Collections.sort(list, new ReverseOrder(myComparator));
    

提交回复
热议问题