同时对两个arrayLists进行排序

假设我有两个ArrayLists:

name: [Four, Three, One, Two] num: [4, 3, 1, 2] 

如果我这样做:Arrays.sort(num),那么我有:

 name: [Four, Three, One, Two] num: [1, 2, 3, 4] 

有没有什么方法可以对num进行排序并将其反映在名称中,这样我最终可能会:

 name: [One, Two, Three, Four] num: [1, 2, 3, 4] 

? 请帮帮我。 我想到了比较器和物体,但根本不知道它们。

你应该以某种方式将namenum字段关联到一个类中,然后列出该特定类的实例。 在此类中,提供compareTo()方法,该方法检查数值。 如果对实例进行排序,那么名称字段也将按您所希望的顺序排列。

 class Entity implements Comparable { 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; } } 

测试代码可能是这样的:

 public static void main(String[] args) { List entities = new ArrayList(); 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 + " "); } 

输出:

1 => 1 2 => 2 3 => 3 4 => 4

您可以使用仅包含索引的数组,而不是对实际数组进行排序

 a[i] = i for i = 0..n 

并且您可以使用自定义比较器基于numeruc数组对此数组进行排序。 例如

 bool compare( int a, int b ) { return num[a] < num[b]; } 

因此,您可以使用这些索引对两个数组进行排序。

如果你没有重复的元素,那么你可以使用像TreeMap这样的有序地图:

 int[] num = {4, 3, 1, 2}; String[] name = {"Four", "Three", "One", "Two"}; TreeMap sortedMap = new TreeMap(); for (int i=0; i 

如果您确实有重复的元素,那么这将无法工作,因为地图的键必须是唯一的。

在某些情况下,创建一个新类只是为了根据给定列表进行多种排序没有多大意义。 我已经创建了一个这样做的函数,但我已经将代码发布在另一个SOpost中,所以我不会重复它。 以下是如何使用它的示例。


用法

下面是一个如何使用该函数对任意类型的多个列表进行排序的示例:

 // The key can be any type that implements Comparable, Dupes are allowed List key = Arrays.asList(4, 3, 1, 2, 1); // List Types do not need to be the same List list1 = Arrays.asList("Four", "Three", "One", "Two", "One"); List list2 = Arrays.asList('d', 'c', 'a', 'b', 'a'); // Sorts key, list1, list2 using key as the sorting key. keySort(key, key, list1, list2); 

输出:

 key: [1, 1, 2, 3, 4] list1: [One, One, Two, Three, Four] list2: [a, a, b, c, d]