william007
william007

Reputation: 18525

Sort by array elements

I have a ArrayList<double[]>

I want to sort the List according to the number in the array in ascending order

first sort by double[0]

then by double[1]

...

lastly by double[n-1] where n is the size of the double array

Is there any simple way to do this in Java?

Considered an example of arraylist that have 4 double arrays

{1,2,3,4,5}
{2,3,4,5,6}
{0,1,2,3,4}
{0,2,2,3,4}

After sorting it will be

{0,1,2,3,4}
{0,2,2,3,4}//first element(0=0) is the same, it looks at the second element, and 2>1
{1,2,3,4,5}
{2,3,4,5,6}

it will first look sort by the first elements, if it is same it will see the second, so on and so forth.

Upvotes: 2

Views: 81

Answers (2)

djechlin
djechlin

Reputation: 60758

You can do it using Arrays.sort or Collections.sort depending on whether your outer collection is an array or a List, with a custom comparator:

public static <T> void sort(T[] a,
        Comparator<? super T> c)

Just write a custom comparator in double[]. Given the object oriented-ness of Java, that will be a class you write implementing Comparator.

There's a similar solution involving Comparable, if you're willing to (you may not be) wrap your double[] in some wrapper class LexicalDouble, with the specified comparison method.

private static class Lexical implements Comparator<double[]> {

    @Override
    public int compare(double[] o1, double[] o2) {
        for (int i = 0; i < o1.length && i < o2.length; i++) {
            if (o1[i] != o2[i]) {
                return o1[i] - o2[i] > 0 ? 1 : -1;
            }
        }

        if (o2.length != o1.length) {
            // how to compare these?
            return o1.length - o2.length;
        }
        return 0;
    }
}

public static void main(String[] args) {
    double[][] a = { { 1, 2 }, { 2, 4 }, { 2, -2 } };
    Arrays.sort(a, new Lexical());
    }

Upvotes: 4

Joe
Joe

Reputation: 111

There is a method you can use:

Arrays.sort();

Sorts the specified array into ascending numerical order.

Upvotes: 1

Related Questions