【问题标题】:Sorting a 2D ArrayList By Each Column按每列对 2D ArrayList 进行排序
【发布时间】:2017-03-05 03:27:22
【问题描述】:

我需要澄清一下如何根据存储在每列中的值对 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 进行排序后,我需要能够执行一组操作。

【问题讨论】:

  • 我目前将代码设置为按第 3 列对 ArrayList 进行排序,表示为:return o1.get(2).compareTo(o2.get(2));

标签: java sorting arraylist


【解决方案1】:

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

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));
    }
}

【讨论】:

    猜你喜欢
    • 2014-11-27
    • 2019-06-14
    • 1970-01-01
    • 1970-01-01
    • 2021-05-18
    • 1970-01-01
    • 2015-07-08
    • 2021-07-26
    • 2013-12-27
    相关资源
    最近更新 更多