Salcey
Salcey

Reputation: 23

Sorting a 2D array with comparator in java for each column

I a working o table sorted for a 2D array with the Array.sort method with a custom comparator

String[] array=new String[]{
"a b c",
"a",
"a b",
"a c"};

I want the output too look as follows

{"a",
 "a b",
 "a b c",
 "a c"}

The compare method for the comparator looks as follows

public int compare(String arg0, String arg1) {
    String[] tempArray0 = arg0.split(" +");
    String[] tempArray1 = arg1.split(" +");

if (!arg0.isEmpty() && !arg1.isEmpty())

    {
        return sortStrings(tempArray0[0], tempArray1[0]);
    }

The sortStrings methods looks like this

 private int sortStrings(String arg0, String arg1) {
    if (arg0.toLowerCase().compareTo(arg1) > 0) {
        return 1;
    } else if (arg0.toLowerCase().compareTo(arg1) < 0) {
        return -1;
    } else {
        return 0;
    }

}

This problem works great if you want to just by first column,but for me it is necessary to check that if the column has the same value it should sort the next column and so on.

I know that in this case I would need to catch a IndexOutOfBounds exception since on of the array which are later divided into 2D array has rows of different sizes.

I just ran into a wall with this problem since I have no idea what kind of loop structure to use here

Upvotes: 0

Views: 874

Answers (1)

Johnny Willer
Johnny Willer

Reputation: 3917

Try this

String[][] array = new String[][] { { "a", "b", "c" }, { "a" }, { "a", "b" }, { "a", "c" } };

        Arrays.sort(array, new Comparator<String[]>() {
            @Override
            public int compare(String[] o1, String[] o2) {

                for (int i = 0; i < o1.length; i++) {

                    if (o2.length == i) return 1;

                    int comp = o1[i].compareTo(o2[i]);

                    if (comp != 0)
                        return comp;   
                }                           
                return -1;
            }
        });

should print:

a
ab
abc
ac

Upvotes: 1

Related Questions