learner learner - 6 months ago 7
Java Question

Sorting two arrays, depending on one array

I have three arrays:

appNames
packageNames
appIcons


Here app names is a string, package names are also string but package name and appIcons are of file type. I want to display all these three things in a list, but in the order of appNames.

Now, I want to sort this array in alphabetical order and also other two arrays, depending on this.

I am working in
Java
, and looking for some easy approach for it.
PHP
has something called
array_multisort()
.

Answer

The native Java approach is to bundle the values from three parallel arrays into a single array or list of objects with three fields, sort it using custom comparer, and then re-distribute the values back into three arrays.

An approach that does not require a new class is to make an index array, sort it with a custom comparator, and use the resulting order of indexes to reorder the three arrays.

For example, if your arrays look like this

a = {"quick", "brown", "fox"};
b = { 5, 10, 1};
c = {.1, .7, .2};

your unsorted index array would look like this

i = {0, 1, 2} // Indexes of quick, brown, fox

your sorted index array would look like this

i = {1, 2, 0} // Indexes of brown, fox, quick

At this point, you can walk the sorted index array, and create new arrays for a, b, and c:

a1 = {"brown", "fox", "quick"}
b1 = {10, 1, 5}
c1 = {.7, .2, .1}
Comments