Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a list with another list

Is it possible to use the Java Collections sort method with a comparator to, as it sorts one list to also sort another list by the index of the original list so that the lists remains paired? Thanks.

like image 430
John Avatar asked Jan 11 '12 21:01

John


2 Answers

You cannot do that with a Comparator. The solution to your problem is to build a third list that holds pairs of corresponding elements from the given lists. Then sort, and copy back to the original lists.

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);
 }
}
like image 93
Itay Maman Avatar answered Oct 28 '22 01:10

Itay Maman


No, because the comparator you would pass in to sort is only given a pair of entries at a time and simply gives back an order over those two elements. The comparator does not see the full list and so can't be used to effectively sort another list at the same time.

What it sounds like you are looking for is a sorted Map. The "second list" is then really just the values of the "key" in the first set. As the keys get reordered, the values will move along with them.

like image 4
cdeszaq Avatar answered Oct 28 '22 00:10

cdeszaq