按列分类2D ArrayList

时间:2017-03-05 03:27:22

标签: java sorting arraylist

我需要澄清一下如何根据每列中存储的值对2D数组列表进行排序。

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Random;


public class ArrayListSorter {
    public static void main(String[] args){
        ArrayList<ArrayList<Double>> myArrayList = new ArrayList<>();
        int numInstances = 10;
        int numAttributes = 10;
        for(int i = 0; i< numInstances; i++){
            myArrayList.add(new ArrayList<Double>());
            for(int j = 0; j < numAttributes; j++){
                Random r = new Random();
                double val = r.nextDouble();
                myArrayList.get(i).add(val);
            }
        }

        Collections.sort(myArrayList, new Comparator<ArrayList<Double>>() {    
            @Override
            public int compare(ArrayList<Double> o1, ArrayList<Double> o2) {
                return o1.get(2).compareTo(o2.get(2));
            }               
        });
        for(int i = 0; i < numInstances; i++){
            System.out.println(myArrayList.get(i));
        }
    }
}

我设置了一个孤立的问题形式,它设置了一个填充了随机双打的2D ArrayList。然后我可以按第一列(或我在代码中指定的任何列)进行排序。我正在努力弄清楚如何迭代到下一列以按下一列中的值重新排序。每次对ArrayList进行排序后,我需要能够执行一组操作。

1 个答案:

答案 0 :(得分:0)

您可以按如下方式实现自定义比较器 -

public class CustomComparator implements Comparator<ArrayList<Double>> {

    private final int index;

    public CustomComparator(int index) {
        this.index = index;
    }

    public int compare(ArrayList<Double> first, ArrayList<Double> second) {
        return first.get(index).compareTo(second.get(index));
    }
}

然后进一步使用它与您的代码按顺序排序 -

for (int j = 0; j < numAttributes; j++) {
    System.out.println("Sorting based on column " + (j+1));
    myArrayList.sort(new CustomComparator(j));
    for (int i = 0; i < numInstances; i++) {
        System.out.println(myArrayList.get(i));
    }
}