This Lambda 8 method came up in one of the suggested answers on leetcode.com: https://leetcode.com/problems/merge-intervals/discuss/21222/A-simple-Java-solution
Below is the method I cannot seem to understand:
int[][] intervals = {{8,10}, {1,3},{2,6},{15,18}}; Arrays.sort(intervals, (i1, i2) -> Integer.compare(i1[0], i2[0]));
I understand that the Arrays.sort()
sorts the array in ascending order and the second argument is supposed to be the range it sorts the array.
What I don’t understand is the i1 and i2 arguments and the Integer.compare()
method that follows.
What exactly are i1
and i2
here? Are they arrays or the integers?
How come we don’t write (int i1, int i2)
? Is this because we have already mentioned Integer afterward?
Advertisement
Answer
I understand that the Arrays.sort() sorts the array in ascending order and the second argument is supposed to be the range it sorts the array.
That is not correct. When you read the javadocs you can see that the second argument is a Comparator – method that defines “rules” on how the array is supposed to be sorted.
int[][]
is an array of arrays of ints. If you take a single element of that, it will be plain array of ints – int[]
. That is the element you want to be comparing in the sort method and that is what i1
and i2
are. But those are just variable names used inside of the lambda – those could be anything else.
Integer.compare(i1[0], i2[0])
this takes first elements of each array and compares based on that.
How come we don’t write (int i1, int i2)? Is this because we have already mentioned Integer afterward?
The method is defined as public static <T> void sort(T[] a, Comparator<? super T> c)
. When you pass int[][]
as the first parameter to it, compilator assumes that second has to be of type Comparator<? super int[]>
. Because of that, parameters of the lambda are int[]
as well.