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 breaking the arraylist into two different arrays and sorting them separately, sort the ArrayList
based on double value in descending order and then break arraylist into two arrays
List<String> list = new ArrayList<>();
list.add("Bahamas,32.2233");
list.add("Zimbabwe,82.2443");
list.add("India,56.2355");
list.add("Australia,24.4363");
List<String> result = list.stream().sorted((a,b)->b.substring(b.lastIndexOf(",")+1).compareTo(a.substring(a.lastIndexOf(",")+1))).collect(Collectors.toList());
System.out.println(result); //[Zimbabwe,82.2443, India,56.2355, Bahamas,32.2233, Australia,24.4363]
Breaking list into double[] array and String[] array
double[] arr = result.stream().mapToDouble(i->Double.parseDouble(i.substring(i.lastIndexOf(",")+1))).toArray();
System.out.println(Arrays.toString(arr)); // [82.2443, 56.2355, 32.2233, 24.4363]
String[] countries = result.stream().map(i->i.substring(0, i.lastIndexOf(","))).toArray(String[]::new);
System.out.println(Arrays.toString(countries)); //[Zimbabwe, India, Bahamas, Australia]
Before java 8 versions
By using `Collections.sort() with custom comparator, and then split the list into two different arrays
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.substring(o2.lastIndexOf(",")+1).compareTo(o1.substring(o1.lastIndexOf(",")+1));
}
});
System.out.println(list); //[Zimbabwe,82.2443, India,56.2355, Bahamas,32.2233, Australia,24.4363]