'Easy sort list 2D by column
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 1:[1]
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));
}
Solution 2:[2]
You can simply do:
list.sort(Comparator.comparingInt(arr -> arr[1]));
or you can also do:
Collections.sort(list, Comparator.comparingInt(arr -> arr[1]));
If you want to sort into a new List<int[]>
you can use stream
:
List<int[]> listSorted = list.stream()
.sorted(Comparator.comparingInt(arr -> arr[1]))
.toList();
Solution 3:[3]
for (int i = 0; i < A.size(); i++) {
int[] temp = A.get(i);
for (int j = i + 1; j < A.size(); j++) {
int[] temp2 = A.get(j);
if (temp[1] > temp2[1]) {
A.set(i, temp2);
A.set(j, temp);
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ryan |
Solution 2 | |
Solution 3 | bjorke07 |