Say I have two ArrayLists:
name: [Four, Three, One, Two]
num: [4, 3, 1, 2]
If I do: Arrays.sort(num), then I have:
name: [
If you don't have repeated elements, then you could just use a sorted Map like a TreeMap instead:
int[] num = {4, 3, 1, 2};
String[] name = {"Four", "Three", "One", "Two"};
TreeMap<Integer,String> sortedMap = new TreeMap<Integer,String>();
for (int i=0; i<num.length; i++) sortedMap.put(num[i], name[i]);
// Resulting sortedMap: {1=One, 2=Two, 3=Three, 4=Four}
If you do have repeated elements then this won't work because the keys of the map must be unique.
You should somehow associate name
and num
fields into one class and then have a list of instances of that specific class. In this class, provide a compareTo()
method which checks on the numerical values. If you sort the instances, then the name fields will be in the order you desire as well.
class Entity implements Comparable<Entity> {
String name;
int num;
Entity(String name, int num) {
this.name = name;
this.num = num;
}
@Override
public int compareTo(Entity o) {
if (this.num > o.num)
return 1;
else if (this.num < o.num)
return -1;
return 0;
}
}
Test code could be like this:
public static void main(String[] args) {
List<Entity> entities = new ArrayList<Entity>();
entities.add(new Entity("One", 1));
entities.add(new Entity("Two", 2));
entities.add(new Entity("Three", 3));
entities.add(new Entity("Four", 4));
Collections.sort(entities);
for (Entity entity : entities)
System.out.print(entity.num + " => " + entity.name + " ");
}
Output:
1 => One 2 => Two 3 => Three 4 => Four
Instead of sorting the actual arrays you can have an array with just indices
a[i] = i for i = 0..n
and you can sort this array based on your numeruc array with a custom comparator. e.g.
bool compare( int a, int b ) { return num[a] < num[b]; }
Thus you have both arrays sorted by using these indices.
In some cases it doesn't make much sense to create a new class just to do multiple sorts based off a given list. I've created a function that does this, but I've posted the code in a another SO post so I wont repeat it. Below is an example of how to use it.
Here is an example of how you can use the function to sort multiple lists of arbitrary types:
// The key can be any type that implements Comparable, Dupes are allowed
List<Integer> key = Arrays.asList(4, 3, 1, 2, 1);
// List Types do not need to be the same
List<String> list1 = Arrays.asList("Four", "Three", "One", "Two", "One");
List<Character> list2 = Arrays.asList('d', 'c', 'a', 'b', 'a');
// Sorts key, list1, list2 using key as the sorting key.
keySort(key, key, list1, list2);
Output:
key: [1, 1, 2, 3, 4]
list1: [One, One, Two, Three, Four]
list2: [a, a, b, c, d]