I have a String array list totalVals. Each entry in totalVals is a string name and a double loc which is joined into a single string before it was inserted into the array list like:
totalVals.add(name + "," + loc);
This is how I am given the data. I have separated the values into a string and double array as follows:
String[] temp;
String[] names = new String[totalVals.size()];
double[] locs = new double[totalVals.size()];
for (int i = 0; i < totalVals.size(); I++){
temp = totalVals.get(i).splot(",");
names[i] = temp[0];
locs[i] = Double.parseDouble(temp[1]);
}
Now however, I want to sort the data and put it back into the array list before returning. I want the locs data to be in descending order, which I can do by using Arrays.sort(locs, Collections.reverseOrder());. But I don't know how to sort names so that the names are still associated with the same locations that they were originally.
Example of totalVals: {"Bahamas,32.2233","Zimbabwe,82.2443","India,56.2355","Australia,24.4363"}
Would be split into:
names = {"Bahamas","Zimbabwe","India","Australia"};
locs = {32.2233,82.2443,56.2355,24.4363};
Which would then be sorted to:
names = {"Zimbabwe","India","Bahamas","Australia"};
locs = {82.2443,56.2355,32.2233,24.4363};
So how would I then sort the two arrays such that the associations at index i in both arrays remain the same?
Instead of turning your array into two arrays, turn it into an ArrayList<Pair>
The Pair class is the following :
public class Pair {
private String country;
private int loc;
public Pair(String country, int loc) {
this.country = country;
this.loc = loc;
}
// getters and setters here
}
And sort your arrays like this :
Collections.sort(array, Comparator.comparingInt(Pair::getLoc));
And then split your array into the two arrays.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With