Java - Sort one array based on values of another array?

algorithm, java, sorting

Solution

In java 8, you can do this

with a lambda:

    String[] strings = new String[]{"string1", "string2", "string3"};
    final int[] ints = new int[]{40, 32, 34};

    final List<String> stringListCopy = Arrays.asList(strings);
    ArrayList<String> sortedList = new ArrayList(stringListCopy);
    Collections.sort(sortedList, (left, right) -> ints[stringListCopy.indexOf(left)] - ints[stringListCopy.indexOf(right)]);

Or better, with Comparator:

    String[] strings = new String[]{"string1", "string2", "string3"};
    final int[] ints = new int[]{40, 32, 34};

    final List<String> stringListCopy = Arrays.asList(strings);
    ArrayList<String> sortedList = new ArrayList(stringListCopy);
    Collections.sort(sortedList, Comparator.comparing(s -> ints[stringListCopy.indexOf(s)]));

Problem

I have an array of Strings that are instances of a class from external code that I would rather not change. I also have an array of ints that was generated by calling a function on each object. So I have A: `[string1, string2, string3]` And B: `[40, 32, 34]` How do I easily sort A such that it is sorted in by the values of B. I have boost available. I want to sort A such that it is in the order: ``` [string2, string3, string1] ``` In javascript you could do this like: ``` B.sort(function(a,b){return A[B.indexOf(a)] < A[B.indexOf(b)];}); ```

Original source

Related problems