2

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]);
    }
});

}
}

1
  • What data types are you using? Share some code please. Also please explain what you have tried so far. Commented Feb 13, 2016 at 18:13

2 Answers 2

2

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).

Sign up to request clarification or add additional context in comments.

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.