Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)];});
like image 672
Reza Avatar asked Feb 17 '15 06:02

Reza


People also ask

How do you sort an array based on another array?

Method 1 (Using Sorting and Binary Search)Create a temporary array temp of size m and copy the contents of A1[] to it. Create another array visited[] and initialize all entries in it as false. visited[] is used to mark those elements in temp[] which are copied to A1[]. Initialize the output index ind as 0.

How do you sort an array and assign it to another array in Java?

You can sort within the array using Arrays. sort() method, or if you want to sort in a different array, you can take following steps: Copy the array to new array. Sort the new array and then sort.

What is relative order array?

The relative order means that in respect to the original order, the new partitioned set will maintain that ordering. In your example that means {1,7,3,10,9,6} become {10,6,1,7,3,9}


1 Answers

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)]));
like image 105
Thermech Avatar answered Nov 16 '22 01:11

Thermech