Vikash Yadav
Vikash Yadav

Reputation: 33

Sort and Reverse 2D array in java

How can I sort and reverse an integer array on basis of integers in second column ? Example-Input--{{1,2},{1,1},{1,3},{1,1},{1,4}} Output--{{1,4},{1,3},{1,2},{1,1},{1,1}} Can anybody point out mistakes in my code, it is giving compilation error.

import java.util.*;
class twod_sort implements Comparator{
public static void main(String []args){
int a[][]={{1,2},{1,1},{1,3},{1,1},{1,4}};
Arrays.sort(numbers, new Comparator<int[]>(){
    public int compare(Integer[] o1, Integer[] o2) {
        return o1[1].compareTo(o2[1]);
    }
});

}
}

Upvotes: 2

Views: 1766

Answers (2)

Palle
Palle

Reputation: 12109

DominicEU's answer does the right job but it could be written down in a shorter way by utilizing Java 8 lambda-syntax:

Arrays.sort(input, (v1, v2) -> Integer.compare(v2[1], v1[1]));

This will sort the input array in reverse order instead of only printing it to the console in reverse order (note the swapped v1 and v2 in the Integer.compare-function).

Upvotes: 2

DominicEU
DominicEU

Reputation: 3631

Something like this will give you the output you'd like

    final Integer[][] data = new Integer[][] {
            new Integer[] { 1, 2 },
            new Integer[] { 1, 1 },
            new Integer[] { 1, 3 },
            new Integer[] { 1, 1 },
            new Integer[] { 1, 4 } };

    Arrays.sort(data, new Comparator<Integer[]>() {
        @Override
        public int compare(final Integer[] obj, final Integer[] obj2) {
            final Integer fistValue = obj[1];
            final Integer secondValue = obj2[1];
            return fistValue.compareTo(secondValue);
        }
    });

    for (int i = data.length - 1; i >= 0; i--) {
        System.out.println(Arrays.toString(data[i]));
    }

Prints the following

[1, 4] [1, 3] [1, 2] [1, 1] [1, 1]

Upvotes: 0

Related Questions