Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a two-dimension ArrayList

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

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

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.

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.

Thanks for help.

like image 709
Believer Avatar asked Apr 05 '12 20:04

Believer


1 Answers

Do something like this:

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

Set COLUMN to whatever column you're sorting on.

Update:

Yes, this won't work at all.

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.

Here is one implementation: http://www.vogella.de/articles/JavaAlgorithmsQuicksort/article.html

like image 114
Sarel Botha Avatar answered Oct 15 '22 08:10

Sarel Botha