Issue
I'm quiet new in Java data manipulation so I need some help if someone have a some good tips. Actually, I want just to find a easy way to sort a 2D list.
I create a list like this:
List<int[]> A = new ArrayList<int[]>();
A.add(new int[] {0,1});
A.add(new int[] {5,40});
A.add(new int[] {7,5});
And then I want to have a result sorted by the second element like:
0 -> 1
7 -> 5
5 -> 40.
I tried something like Arrays.sort(A.toArray(), (int[]a, int[]b) -> a[0] - b[0]);
but it doesn't work.
Is there a simple solution to do that sort list?
Solution
Try this:
List<Integer[]> A = new ArrayList<>();
A.add(new Integer[] {0,1});
A.add(new Integer[] {5,40});
A.add(new Integer[] {7,5});
A.sort(Comparator.comparingInt(a -> a[1]));
for (Integer[] a : A) {
System.out.println(Arrays.toString(a));
}
Answered By - Ryan
Answer Checked By - Terry (JavaFixing Volunteer)