bumper_boy2000
bumper_boy2000

Reputation: 13

Sorting a 2D arraylist based on first element of nested arraylist

I'm having an issue whereby the original 2D arraylist, after sorting, outputs in the following format:

[639.5, 134, -2]
[639.524, 131, -1]
[640.478, 179, -2]
[647.968, 192, -2]
[649.068, 199, -2]
[65.581, 3, -1]
[66.387, 6, -1]
[66.726, 7, -1]
[660.182, 194, -1]

and I'd like to sort based on the first column only. Hence, my expected result should be this instead:

[65.581, 3, -1]
[66.387, 6, -1]
[66.726, 7, -1]
[639.5, 134, -2]
[639.524, 131, -1]
[640.478, 179, -2]
[647.968, 192, -2]
[649.068, 199, -2]
[660.182, 194, -1]

Somehow the Collections.sort() method sorts the list as if it's a String, hence "0" is bigger than ".", not knowing that the first column is made up of double values. Can anyone assist me in this? Thanks!

Upvotes: 0

Views: 2509

Answers (2)

user1237385
user1237385

Reputation:

Use Double.compare() method.... Pass that first column value in this method it will work...

For example :

In main file :

 Collection.sort(arraylist variable,new PositionComparator());

Other Class :

public class PositionComparator implements Comparator ArrayList<ArrayList> {
    public int compare(ArrayList<ArrayList> o1, ArrayList<ArrayList> o2) {
        double val1, val2;
        val1 = Double.parseDouble(o1.get("your first value"));
        val2 = Double.parseDouble(o2.get("your second value"));
        return Double.compare(val1, val2);
    }
}

Hope this will help...

Upvotes: 2

CoNgL3
CoNgL3

Reputation: 56

Collection.sort orders the list in its natural order so you might want to try overriding the compareTo() method

Upvotes: 0

Related Questions