2

I've been looking around on the internet trying to find out how to sort a multidimensional array by column and i found a way that works but I'm not sure exactly how it works. Can someone explain it to me?

Arrays.sort(data, (int[] num1, int[] num2) ->
    Integer number1 = num1[1];
    Integer number2 = num2[1];
    return number2.compareTo(number1);
});

in this care the code sorts the array [][] in descending order by the second column.

1
  • This code is for Java 8 and uses lambda expressions. You are missing {. Commented Aug 6, 2015 at 18:07

1 Answer 1

3

A two dimensional array is an array whose elements are arrays (int[] in your case). Therefore, in order to sort such an array, you should supply a comparator that compares int[] objects. This is exactly what the lambda expression in your code snippet does. It accepts two int[] objects and determines their relative order by comparing the elements at the second position (i.e. index 1) of the two arrays.

The lambda expression is a feature added in Java 8. It allows you to supply an implementation to a functional interface (which is an interface with a single method, such as Comparator<int[]>, whose single method is int compare (int[] first, int[] second)) without most of the syntax required for anonymous class instances.

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

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.