在某些情况下,仅仅为了排序而创建一个新的类并没有太多意义。
这里提供了一个函数,可以用来对任意数量、任意类型的列表(
List<?>
)根据一个关键字列表(
List<T implements Comparable>
)进行排序。请点击
此处查看 Ideone 示例。
用法
以下是使用该函数对多个任意类型的列表进行排序的示例:
List<Integer> ids = Arrays.asList(0, 1, 2, 3);
List<String> colors = Arrays.asList("blue", "yellow", "red", "black");
List<String> clothes = Arrays.asList("shoes", "pants", "boots", "coat");
concurrentSort(ids, ids, colors, clothes);
concurrentSort(colors, ids, colors, clothes);
concurrentSort(clothes, ids, colors, clothes);
输出:
// Sorted By ID:
ID: [0, 1, 2, 3]
Colors: [blue, yellow, red, black]
Clothes: [shoes, pants, boots, coat]
// Sorted By Color:
ID: [3, 0, 2, 1]
Colors: [black, blue, red, yellow]
Clothes: [coat, shoes, boots, pants]
// Sorted By Clothes:
ID: [2, 3, 1, 0]
Colors: [red, black, yellow, blue]
Clothes: [boots, coat, pants, shoes]
代码
可以在这里找到一个Ideone示例,其中包括参数验证和测试用例。
public static <T extends Comparable<T>> void concurrentSort(
final List<T> key, List<?>... lists){
List<Integer> indices = new ArrayList<Integer>();
for(int i = 0; i < key.size(); i++)
indices.add(i);
Collections.sort(indices, new Comparator<Integer>(){
@Override public int compare(Integer i, Integer j) {
return key.get(i).compareTo(key.get(j));
}
});
Map<Integer,Integer> swapMap = new HashMap<Integer, Integer>(indices.size());
List<Integer> swapFrom = new ArrayList<Integer>(indices.size()),
swapTo = new ArrayList<Integer>(indices.size());
for(int i = 0; i < key.size(); i++){
int k = indices.get(i);
while(i != k && swapMap.containsKey(k))
k = swapMap.get(k);
swapFrom.add(i);
swapTo.add(k);
swapMap.put(i, k);
}
for(List<?> list : lists)
for(int i = 0; i < list.size(); i++)
Collections.swap(list, swapFrom.get(i), swapTo.get(i));
}
注意: 运行时间为 O(mlog(m) + mN)
,其中 m
是列表的长度,N
是列表的数量。通常情况下,m >> N
,因此运行时间不会比仅对键进行排序的时间 O(mlog(m))
更显著。