0

有 5 个条目存储在ArrayList<ArrayList<Double>> selected. 这些条目中的每一个都由两个参数指定 -rankcd

rank = [1.0, 2.0, 3.1, 1.2, 2.1]
cd = [6.2, 5.2, 7.1, 8.0, 1.1]

我需要对这些条目进行排序,首先,按rank其次,按cd降序排列(即 3.1、2.1、2.0、1.2、1.1)。第二个排序 (by cd) 必须应用于已经按 排序的条目rank

ArrayList<Double> rank = new ArrayList<Double>(); 
ArrayList<Double> cd = new ArrayList<Double>();

ArrayList<ArrayList<Double>> selected = new ArrayList<ArrayList<Double>>();

for (int i=0; i<len; i++) {
    rank.add(getRank(i));
    cd.add(getCub_len(i));
}
selected.add(0,rank);
selected.add(1,cd);

Comparator<ArrayList<Double>> comparatorRank = new Comparator<ArrayList<Double>>() 
{
    public int compare(ArrayList<Double> a, ArrayList<Double> b) 
    {
        return (int) (a.get(0) - b.get(0));
    }
};

Comparator<ArrayList<Double>> comparatorCD = new Comparator<ArrayList<Double>>() 
{
    public int compare(ArrayList<Double> a, ArrayList<Double> b) 
    {
        return (int) (a.get(1) - b.get(1));
    }
};

Collections.sort(selected, comparatorRank);
Collections.sort(selected, comparatorCD);

问题是我不知道如何在订购之前获取已分配给条目的 ID。例如,这是一个无序的ID序列:1、2、3、4、5,这是排序后的ID序列:5、3、4、1、2。如何获得这些ID?

4

1 回答 1

0

这就是我将如何处理它...

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class SortPairs {

    public static void main(String[] args) {
        List<Double> rank = new ArrayList<Double>(Arrays.asList(1.0, 2.0, 3.1, 1.2, 2.1)); 
        List<Double> cd = new ArrayList<Double>(Arrays.asList(6.2, 5.2, 7.1, 8.0, 1.1));

        List<Pair<Double, Double>> pairs = new ArrayList<Pair<Double, Double>>(rank.size());
        for (int i = 0; i < rank.size(); ++i)
            pairs.add(new Pair<Double, Double>(rank.get(i), cd.get(i)));

        Collections.sort(pairs);

        ListIterator<Double> rankIter = rank.listIterator();
        ListIterator<Double> cdIter = cd.listIterator();
        for (Pair<Double, Double> pair : pairs) {
            System.out.println(String.format("[rank = %.1f, cd = %.1f", pair.getT1(), pair.getT2()));
            rankIter.next();
            cdIter.next();
            rankIter.set(pair.getT1());
            cdIter.set(pair.getT2());
        }
    }

   public static class Pair <T1 extends Comparable<? super T1>, T2 extends Comparable<? super T2>> implements Comparable<Pair<T1, T2>> {
      private final T1 t1;
      private final T2 t2;

      public Pair(T1 t1, T2 t2) {
         this.t1 = t1;
         this.t2 = t2;
      }

      public T1 getT1() {
          return t1;
      }

      public T2 getT2() {
          return t2;
      }

      @Override
      public int compareTo(Pair<T1, T2> other) {
          return t1.equals(other.t1) ?
                 other.t2.compareTo(t2) : 
                 other.t1.compareTo(t1);
      }
   }
}
于 2013-11-02T16:29:53.477 回答