Can I sort an array based on second arrray?
I mean, lets say
a[]=[2,5,4,3]
c[]=[800,1600,200,400]
c[i] and a[i] are related for same i.
I want to sort a such that a[]=[5,2,3,4] in decreasing order of values stored in c because 5->1600 , 2->800 and so on.
Can it be done in a single line, like below (below is just structure of answer I am expecting)
Arrays.sort(a, (i, j) -> Integer.compare(c[j], c[i]))
I am doing it via lengthy method of using extra space.
Arrays.sort(a, (i, j) -> Integer.compare(c[Arrays.asList(a).indexOf(j)], c[Arrays.asList(a).indexOf(i)]));If that is acceptable let me know, I can add it as an answerc[i]anda[i]are related, then why don't you create a class or record for it? Example:record Employee(int id, int salary) {}.IntStreamshenanigans. It'll be a long and awkward line, more difficult to understand and probably less efficient than a more explicit solution -- like most applications of streams that aren't aimed at one of the "sweet spots" of the API.int[] result = new int[4]; result = IntStream.range(0, a.length).boxed().sorted((i, j) -> Integer.compare(c[j], c[i])).map(i -> a[i]).mapToInt(Integer::intValue).toArray();