javasortingcollectionscomparatorcomparable

JAVA Collections Modified Sorting


List<Integer> list = new ArrayList<>();
for(int i = 0 ; i <= 8 ; i ++){
  list.add(i+1);
}
Collections.sort(list,(a, b)-> (a%b==0) ? 1 : (a%b==1) ? -1 : 0 );
list.forEach(System.out::println);

why the output is 1 4 3 5 7 2 6 9 8? How is the sorting done? Please Explain it briefly.


Solution

  • Here is a print-out of the values, as the comparison occurs.

    a= 2, b= 1, (2 % 1 = 0), returns  1
    a= 3, b= 2, (3 % 2 = 1), returns -1
    a= 3, b= 2, (3 % 2 = 1), returns -1
    a= 3, b= 1, (3 % 1 = 0), returns  1
    a= 4, b= 3, (4 % 3 = 1), returns -1
    a= 4, b= 1, (4 % 1 = 0), returns  1
    a= 5, b= 3, (5 % 3 = 2), returns  0
    a= 5, b= 2, (5 % 2 = 1), returns -1
    a= 6, b= 3, (6 % 3 = 0), returns  1
    a= 6, b= 2, (6 % 2 = 0), returns  1
    a= 7, b= 5, (7 % 5 = 2), returns  0
    a= 7, b= 6, (7 % 6 = 1), returns -1
    a= 7, b= 2, (7 % 2 = 1), returns -1
    a= 8, b= 5, (8 % 5 = 3), returns  0
    a= 8, b= 2, (8 % 2 = 0), returns  1
    a= 8, b= 6, (8 % 6 = 2), returns  0
    a= 9, b= 7, (9 % 7 = 2), returns  0
    a= 9, b= 6, (9 % 6 = 3), returns  0
    a= 9, b= 8, (9 % 8 = 1), returns -1
    

    Here is the modified code.

    List<Integer> list = new ArrayList<>();
    for(int i = 0 ; i <= 8 ; i ++){
        list.add(i+1);
    }
    list.sort((a, b) -> {
        int value = (a % b == 0) ? 1 : (a % b == 1) ? -1 : 0;
        System.out.printf("a= %d, b= %d, (%1$d %% %2$d = %3$d), ", a, b, a % b);
        System.out.printf("returns %2d%n", value);
        return value;
    });
    list.forEach(System.out::println);