1

I have a 2D array of type int i.e [][]intervals Using Java 8 syntax, I can sort like this

Arrays.sort(intervals, (int[] o1, int[] o2) -> {
    if (o1[1] != o2[1]) return o1[1] - o2[1];
    return o1[0] - o2[0];
});

Basically, I understand I have the logic defined as the 2nd argument which is Comparator

I want to just for the sake of learning, do something like this

var c = Comparator.<int[]>.comparing(not able to put the 2 arguments properly here)

This also works, but I am not able to use the var and Comparator style above

Comparator<int[]> c = (int[] i1, int[] i2) -> {
    if (i1[0] == i2[0]) return i1[1] - i2[1];
    return i1[0] - i2[0];
}

I am unable to get the syntax right. I got it working as below as well, but that is not the Lambda style as I am trying to do above

var c = new Comparator<int[]>() {
    @Override
    public int compare(int[] o1, int[] o2) {
        if (o1[1] != o2[1]) return o1[1] - o2[1];
        return o1[0] - o2[0]; 
    }
};

Arrays.sort(intervals,c);
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
curiousengineer
  • 2,196
  • 5
  • 40
  • 59
  • You'd need `Comparator.comparing(...).thenComparing(...)`. The lambda for `comparing`/`thenComparing` should only take 1 parameter. See [here](https://stackoverflow.com/q/71548399/5133585) for a more detailed explanation. – Sweeper Mar 31 '23 at 02:10
  • 1
    Since you tagged your question with `java-8`, you can’t use `var` at all. If you are not using Java 8, don’t use the `java-8` tag. – Holger Mar 31 '23 at 11:12

1 Answers1

3

Here is some sample code to demonstrate how to make comparators with multiple criteria work:

int[][] vals = {{3, 2}, {2, 2}, {1,2}, {2, 3}, {4, 1}};
Comparator<int[]> order = Comparator
    .comparingInt((int[] vs) -> vs[1])
    .thenComparingInt((int[] vs) -> vs[0]);
Arrays.sort(vals, order);
Arrays.stream(vals).map(Arrays::toString).forEach(System.out::println);

The comparingInt methods say to compare the integers extracted from the array using the given lambda. You could just use comparing and thenComparing - it would just be slightly less efficient as it boxes the values before comparing them.

sprinter
  • 27,148
  • 6
  • 47
  • 78