If you are using Java 8 you could create a stream of array2
sorted according to array1
as follows:
int[] array3 = IntStream.range(0, array1.length).boxed()
.sorted(Comparator.comparingInt(i -> array1[i]))
.mapToInt(i -> array2[i])
.toArray();
Hopefully you can see how that works: it produces a stream of indices, sorts them according to the values in the first array, maps them to the values in the second array and then converts back to an array. Having to box and unbox is only to allow the custom sort (which IntStream
doesn't support for some reason).
Here's some sample code to demonstrate:
int[] array1 = { 5, 4, 3, 2, 1 };
int[] array2 = { 10, 20, 30, 40, 50 };
System.out.println(Arrays.toString(IntStream.range(0, array1.length).boxed()
.sorted(Comparator.comparingInt(i -> array1[i]))
.mapToInt(i -> array2[i]).toArray()));
This is assuming the type is int[]
but it's easily convertible to any other types. The same approach works for indexible collections.
If the array is of objects then you can use Arrays.sort(T[], Comparator)
to sort in place. Java doesn't provide an equivalent for primitive types unfortunately - the assumption is that you want to sort by their natural order.