What's the sort order of Java's Collections.sort(list, comparator)? small to big or big to small?

前端 未结 4 1834

Apparently, it\'s not documented or I missed it.

Here\'s the link to the documentation and below\'s the text as an image:

EDIT(17/5): I think to

4条回答
  •  误落风尘
    2021-02-01 02:21

    The documentation of Comparator.compareTo(o1, o2) method says

    Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

    So if you want to sort from natural ordering , that is small to big, then you should write the implementation as defined in the documentation

    public int compareTo(Integer o1, Integer o2) {
         int v1 = (o1);
         int v2 = (o2);
         if(v1 == v2) {
            return 0;
         }
         if(v1 < v2) {
            return -1; //return negative integer if first argument is less than second
         }
         return 1;
    }
    

    If you want the sorting to be in reverse order, that is big to small

    public int compareTo(Integer o1, Integer o2) {
         int v1 = (o1);
         int v2 = (o2);
         if(v1 == v2) {
            return 0;
         }
         if(v1 < v2) {
            return 1;  //do the other way
         }
         return -1;
    }
    

提交回复
热议问题