是否可以将
Java Collections排序方法与比较器一起使用,因为它会对一个列表进行排序,以便按原始列表的索引对另一个列表进行排序,以便列表保持配对?谢谢.
解决方法
你不能用比较器做到这一点.您的问题的解决方案是构建第三个列表,该列表包含给定列表中的对应元素对.然后排序,并复制回原始列表.
public class Pair<X,Y> {
public final X x;
public final Y y;
public Pair(X x,Y y) {
this.x = x; this.y = y;
}
}
public static<X,Y> void sortTwoLists(List<X> xs,List<Y> ys,final Comparator<X> c) {
if (xs.size() != ys.size())
throw new RuntimeException("size mismatch");
List<Pair<X,Y>> temp = new ArrayList<Pair<X,Y>>();
for (int i = 0; i < xs.size(); ++i)
temp.add(new Pair<X,Y>(xs.get(i),ys.get(i)));
Collections.sort(temp,new Comparator<Pair<X,Y>>() {
@Override
public int compare(Pair<X,Y> a,Pair<X,Y> b) {
return c.compare(a.x,b.x);
}
});
for(int i = 0; i < xs.size(); ++i) {
xs.set(i,temp.get(i).x);
ys.set(i,temp.get(i).y);
}
}