如何对二维 ArrayList 进行排序 [英] How to sort a two-dimension ArrayList

查看:83
本文介绍了如何对二维 ArrayList 进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含双精度值的二维 ArrayList:

I have a two-dimension ArrayList that contains double values:

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

与经典数组类比,我想对这个矩阵的列"进行排序:我想在子 ArrayLists 中取出具有相同索引的项目,然后对它们进行排序.就像为每一列调用 Collections.sort() 一样......行是指外层和内层是列.

In analogy with classic arrays , I would like to sort the "cols" of this matrix :I want to take the items having the same index in the sub ArrayLists, and then sort them. Like calling Collections.sort() for every column... By rows I mean the outer level and inner level are columns.

这样做的正确方法是什么?我想过迭代矩阵来反转它,然后用 Collections.sort() 对每一行进行排序?但也许这不是最好的解决方案,因为矩阵大约是 400*7000 .

What is the proper way to do this? I thought about iterating over the matrix to invert it and then sort each row with Collections.sort() ? but maybe it's not the best solution because the matrix is about 400*7000 .

我不能使用经典数组,因为矩阵的大小未知.

I can't use classic arrays since the size of the matrix is unknown.

感谢您的帮助.

推荐答案

做这样的事情:

    final int COLUMN = 5;
    Comparator<ArrayList<Double>> myComparator = new Comparator<ArrayList<Double>>() {
        @Override
        public int compare(ArrayList<Double> o1, ArrayList<Double> o2) {
            return o1.get(COLUMN).compareTo(o2.get(COLUMN));
        }
    };
    Collections.sort(list, myComparator);

将 COLUMN 设置为您要排序的任何列.

Set COLUMN to whatever column you're sorting on.

更新:

是的,这根本行不通.

我喜欢 ahanin 的第二个建议,即制作您自己的 List 来包装您的原始 List.您还必须包装 get() 返回的对象,以便变量wrappedList 包含列值,并且wrappedList.get(0) 还返回一列值.然后排序可以工作.我想知道您必须为 Collections.sort() 实现哪些最少的方法才能在您的 List 上工作.

I like ahanin's second suggestion to make your own List which wraps your original List. You would have to wrap the object returned by get() as well so that the variable wrappedList contains the column values and wrappedList.get(0) also returns a column of values. Then the sorting can work. I wonder what the minimum methods are that you have to implement for Collections.sort() to work on your List.

采用其他人的快速排序并使其适用于您的列表可能是最简单的.

It would probably be easiest to just take someone else's quicksort and make it work with your list.

这是一个实现:http://www.vogella.de/articles/JavaAlgorithmsQuicksort/article.html

这篇关于如何对二维 ArrayList 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆