Java – use another list to sort the list

Can the Java collections sorting method be used with a comparator because it sorts one list to sort another by the index of the original list so that the lists remain paired? thank you.

Solution

You can't do this with a comparator The solution to your problem is to build a third list that contains the corresponding element pairs in a given list Then sort and copy back to the original list

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);
 }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>