使用其他列表对列表进行排序

Joh*_*ohn 6 java sorting arraylist

是否可以将Java Collections排序方法与比较器一起使用,因为它会对一个列表进行排序,以便按原始列表的索引对另一个列表进行排序,以便列表保持配对?谢谢.

Ita*_*man 4

你不能用比较器来做到这一点。问题的解决方案是构建第三个列表,其中包含给定列表中的成对对应元素。然后排序,并复制回原始列表。

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);
 }
}
Run Code Online (Sandbox Code Playgroud)