简体   繁体   中英

Deep sorting in 2d array

I need to achieve a functionality in java similar to sql sort where in i have a function where i pass a 2d array along with 2 column indexes, this function should return a sorted 2d array on the provided column indexes.

In short I need to sort the 2d array on 2 columns.

I was able to achieve the sort on 1 column wise , PFB the code for the same.

Arrays.sort(arr, new Comparator(){
        private int col ;
         public int compare(Object o1, Object o2) {
    String[] s1 = (String[])o1;
    String[] s2 = (String[])o2;
    return s1[col].compareTo(s2[col]);
    }

    private Comparator init(int var){
    col = var;
    return this;
}
}.init(0)
);

But i need to enhance this functionality to sort based on 2 columns in 2d array. I request experts to help me out in this.

Example Input array

1 2 3 4
1 8 2 8 
8 6 10 11
5 6 7 8
1 6 2 6 

Output : On sorting with Column 2,3 1 2 3 4 1 6 2 6 5 6 7 8 8 6 10 11 1 8 2 8

Thanks in advance, Raju

Just compare by the second column when the first ones are equals, like that:

int equal = s1[col].compareTo(s2[col]);
return equal == 0 ? s1[col2].compareTo(s2[col2]) : equal;

Please also note that you are comparing strings (a lexicographical comparison), not numbers, so "10" would be less then "2", resulting in:

1 2 3 4 
8 6 10 11 
1 6 2 6 
5 6 7 8 
1 8 2 8 

when you sort by columns 2 and 3.

If that is not what you want, just convert you data to integers and compare then numerically.

You can also use Comparator.thenComparing to do the same thing:

thenComparing(Comparator other) Returns a lexicographic-order comparator with another comparator.

If this Comparator considers two elements equal, ie compare(a, b) == 0, other is used to determine the order.

Arrays.sort(array,
    Comparator.<String[],String>
    comparing(row -> row[1])
   .thenComparing(row2 -> row2[2])
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM