I am trying to write a function that takes two parameters, int[] arr1
and int[] arr2
. Then, it should sort arr1
in the order given in arr2
. For example, if arr1
is [5,7,9,10,7,5]
and arr2
is [7,9,10,5]
, the function should return [7,7,9,10,5,5]
, sorting arr1
in the order elements in arr2
are indexed.
I wrote my code as below, but I keep on getting an error at Arrays.sort. I think I am using lambda incorrectly. Can you specify what I am doing wrong?
public int[] relativeSortArray(int[] arr1, int[] arr2) {
Map<Integer, Integer> elemToInd = new HashMap<Integer, Integer>();
for (int i = 0; i < arr2.length; i++) {
elemToInd.put(arr2[i], i);
}
Arrays.sort(arr1, (int n1, int n2) -> elemToInd.get(n1) - elemToInd.get(n2));
return arr1;
}