首页 > 解决方案 > 根据JAVA中的列对动态二维数组进行排序

问题描述

我创建了一个数组的 ArrayList,它可能包含 n 行但两个固定列。例如

ArrayList<int[]> rows = new ArrayList<>();
rows.add(new int[] {3, 100});
rows.add(new int[] {4, 150});
rows.add(new int[] {4, 80});
rows.add(new int[] {2, 90});
rows.add(new int[] {2, 300});

请注意,可能会有更多行。我想根据第二列对这些行列表进行排序。我该怎么做呢?如果有任何其他不基于 ArrayList 的更好的方法来做到这一点,也请告诉我。

标签: java

解决方案


比较器::comparingInt

如下所示使用它:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

public class Main {
    public static void main(String[] args) {
        ArrayList<int[]> rows = new ArrayList<>();
        rows.add(new int[] { 3, 100 });
        rows.add(new int[] { 4, 150 });
        rows.add(new int[] { 4, 80 });
        rows.add(new int[] { 2, 90 });
        rows.add(new int[] { 2, 300 });

        // Sort arrays (i.e. rows) on the value at index, 1 (i.e. second column)
        rows.sort(Comparator.comparingInt(e -> e[1]));

        // Display
        rows.forEach(e -> System.out.println(Arrays.toString(e)));
    }
}

输出:

[4, 80]
[2, 90]
[3, 100]
[4, 150]
[2, 300]

推荐阅读