0

I am using lambda expression to sort 2D array based on multiple column but it failed while compiling.

public static void 2DarraySort(int[][] box) {
    Arrays.sort(box, Comparator.comparingInt(row -> row[0]).thenComparingInt(row -> row[1]));
}

Can someone please tell what wrong I am doing?

Error message:

array required, but java.lang.Object found
0009laH
  • 1,960
  • 13
  • 27
Beginner
  • 145
  • 7

1 Answers1

0

This would work fine if you have not chained the comparators:

Arrays.sort(box, Comparator.comparingInt(row -> row[0]));

However, when comparators are chained, the type of the objects being compared need to be specified explicitly, which may be done in two ways:

  1. Provide type in comparingInt/comparing
Arrays.sort(box, Comparator
    .<int[]>comparingInt(row -> row[0])
    .thenComparingInt(row -> row[1])
);
  1. Specify row type in lambda:
Arrays.sort(box, Comparator
    .comparingInt((int[] row ) -> row[0])
    .thenComparingInt(row -> row[1])
);
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42