JAVA Collections Modified Sorting

62 Views Asked by At
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.

2

There are 2 best solutions below

2
Reilas On BEST ANSWER

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);
1
Cosemuckel On

This should comparator check whether a is divisible by b using the modulo operator (%).

  • If a is divisible by b, then it returns 1, indicating that a should come after b in the sorted list
  • If a leaves a remainder of 1 when divided by b, then it returns -1, indicating that a should come before b in the sorted list.
  • If neither of these conditions is true, then it returns 0, indicating that a and b are equal in terms of sorting, no swapping will be performed.

However look at the case a = 1, b = 2:

  • 1 % 2 == 1 -> a should be after b
  • 2 % 1 == 1 -> b should be after a

These two are contradictory!

This is why, as explained in the comments comparing a and b should return the opposite sign as comparing b and a.