java - 根据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 的更好的方法来做到这一点,也请告诉我。
解决方案
比较器::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]
推荐阅读
- r - 逐字确定多字串的(不)相似性
- asp.net - 我们可以隐藏 Content-Security-Policy 错误日志的 URL 吗?
- matlab - 通过 GPML 实现 4-D 高斯过程回归的问题
- javascript - 如何在构建模式下以不同方式加载 index.html 中的外部脚本文件?(Vue.js)
- mysql - MySql - 在列别名中使用数据库名称
- android - 如何停止阻塞的活页夹线程?
- android - Android FCM 推送日志
- mysql - 将使用另一个表中的值添加新行的 SQL 查询
- python - 通过 readline 读取动态更新的日志文件
- google-forms - 根据先前的响应验证谷歌表单响应