I am looking to sort an arraylist of arraylist of doubles and I require help?

I was informed that I need to implement comparator or comparable and then use the collection.sort to sort the list of list in order...

ArrayList<ArrayList> list = new ArrayList<ArrayList>()

If you look at the list of list as the following example:

c1-5.0,4.5,10.3,3.5

c2-2.5,1.0,7.8,8.6

c3-6.0,5.6,9.6,9.5

It show go to this

c1-2.5,1.0,7.8,3.5

c2-5.0,4.5,7.8,8.6

c3-6.0,5.6,10.3,9.5

## All 4 Replies

An ArraylIst of ArrayLists is like a 2d array. Which means that there's no single definition of what it means to sort it. Eg
Sort each sub list ?
sort the sublists within the main list according to some criteria ?
sort all of the data and store the result in the same sized 2d array?
(etc).

You need to specify what you mean by sort in this case.

ps: the `Double` class already implememnts `Comparable`, so you can use `Collections.sort` on a List of Doubles without any other code.

Here's a way that is in place, that uses bubble sort.

``````  public static void sortColumns(ArrayList<ArrayList<Double>> arr){
int limit = arr.size();
boolean isSwapped = false;
for(int col = 0; col < limit; ++col){
do{
isSwapped = false;
for(int row = 0; row < limit - 1; ++row){
if(arr.get(row).get(col) > arr.get(row+1).get(col)){
swap(arr,row,col,row+1,col);
isSwapped = true;
}
}
}while(isSwapped);

}
}
private static void swap(ArrayList<ArrayList<Double>> arr, int rowA, int colA, int rowB, int colB){
Double temp = arr.get(rowA).get(colA);
arr.get(rowA).set(colA,arr.get(rowB).get(colB));
arr.get(rowB).set(colB, temp);
}``````

Why write your own bubble sort when `Collections.sort` exists and does it better?

How would you write a function for Collection.sort to do that? It doesn't normally sort by columns.

commented: Good point, :( +15
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.