按列对列表2D进行简单排序



我是Java数据处理领域的新手,所以如果有人有一些好的技巧,我需要一些帮助。实际上,我只是想找到一种简单的方法来对2D列表进行排序。

我创建了一个这样的列表:

List<int[]> A = new ArrayList<int[]>();
A.add(new int[] {0,1});
A.add(new int[] {5,40});
A.add(new int[] {7,5});

然后我想得到一个按第二个元素排序的结果,比如:

0 -> 1
7 -> 5
5 -> 40.

我试过Arrays.sort(A.toArray(), (int[]a, int[]b) -> a[0] - b[0]);之类的东西,但不起作用。

有没有一个简单的解决方案来做排序列表?

您可以简单地执行:

list.sort(Comparator.comparingInt(arr -> arr[1]));

或者你也可以做:

Collections.sort(list, Comparator.comparingInt(arr -> arr[1]));

如果你想排序到一个新的List<int[]>,你可以使用stream:

List<int[]> listSorted = list.stream()
.sorted(Comparator.comparingInt(arr -> arr[1]))
.toList();

试试这个:

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

最新更新