Java: Sort Arraylist with related array
I am using java trying to create a program.
What I am trying to do is sort arraylist and then sort a seperate array with the same order. I know how to sort an arrylist but the problem is I have a seperate ar开发者_开发百科ray where each element is related to an element in the arraylist.
for example here is a possible situation:
String[] array = {"U R F", "B' F2", "L' D"}
arraylist<Double> = {"2.03", "4.32", "1.23"}
(I know that an arraylist isn't initialized like that I did it for simplicity)
What I want to end up with is this:
String[] array = {"L' D", "U R F", "B' F2"}
arraylist<Double> = {"1.23", "2.03", "4.32"}
With the array and arraylist sorted by arraylist numerically.
I suggest you create a bean with 2 fields, one field's value comes from you String array and another field's value comes from your ArrayList. Add the Bean objects into a Collection object and sort.
As long as your companion array contains unique values, you can build a SortedMap whose key-value pairs are made from the ArrayList and the Array respectively. Read out the values of the SortedMap in order into the resulting array.
Here is a complete example:
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* Not great code; it just illustrates an idea.
*/
public class SortExample {
/**
* Shows how to sort an array based on the way a "companion" list
* would sort. <strong>ASSUMPTION</strong>: The values in the companion
* list must be unique!
*/
public static void main(String[] args) {
String[] names = {"two", "seven", "six", "eight", "one"};
List<Integer> numbers = Arrays.asList(2, 7, 6, 8, 1);
// Note: This only works if names and numbers are the same size....
SortedMap<Integer, String> pairs = new TreeMap<Integer, String>();
for (int i = 0; i < names.length; i++) {
pairs.put(numbers.get(i), names[i]);
}
// Note: This destroys the original array
int i = 0;
for (Map.Entry<Integer, String> e : pairs.entrySet()) {
names[i++] = e.getValue();
}
System.out.println(Arrays.toString(names));
}
}
If you know how to sort whats the problem? use the sorting algorithm of your choice and when (after the compare) you swap elements of arraylist, you just have to swap the according elements of the array
If you are good with data saving types, I suggest you to use map.But it can be complicated a bit so make a copy of array that has the numbers.Sort one of them and other one must stay original.After that find each numbers new place in the sorted list and save the number in a int array.In the last step initialize a new array list and add each element to their new places in the array.Hope it helps,good luck.
精彩评论