java - Java ArrayList 按相同顺序对两个列表进行排序
问题描述
我在 Java 中有两个 ArrayList。两个列表都未排序。
ArrayList<Integer> listOne = new ArrayList<>();
listOne.add(2);
listOne.add(1);
listOne.add(4);
listOne.add(8);
listOne.add(6);
ArrayList<String> listTwo = new ArrayList<>();
listTwo.add("ant");
listTwo.add("bear");
listTwo.add("cat");
listTwo.add("dog");
listTwo.add("zebra");
我想按自然顺序对 listOne 进行排序,并且 listTwo 的每个项目都应根据 listOne 中的位置进行排序:
到目前为止,我所拥有的是:
Collections.sort(listOne);
for (int i = 0; i < listOne.size(); i++) {
int intTest = listOne.get(i);
String stringTest = listTwo.get(i);
System.out.println(intTest);
System.out.println(stringTest);
}
这打印:
1 ant, 2 bear, 4 cat , 6 dog , 8 zebra
我预期的打印输出是:
1 bear, 2 ant, 4 cat, 6 zebra, 8 dog
因此,当 listOne 的项目“1”将位置从第 2 位更改为第 1 位时,listTwo 中位于第 2 位的项目“bear”也应该打印在第 1 位。
最简单有效的方法是什么?
解决方案
创建一个有序的索引列表:
int n = listOne.size();
assert n == listTwo.size();
Integer[] indices = new Integer[n];
for (int i = 0; i < n; ++i) {
indices[i] = i;
}
使用比较器对该列表进行排序,该比较器通过查看 listOne 中的相应元素来比较索引。
Arrays.sort(
indices,
new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
return listOne.get(a).compareTo(listOne.get(b));
}
});
现在您可以使用索引对两个列表重新排序:
static <T> void reorder(Integer[] indices, List<T> mutatedInPlace) {
List<T> tempSpace = new ArrayList<T>(indices.length);
for (int index : indices) {
tempSpace.add(mutatedInPlace.get(index);
}
mutatedInPlace.clear();
mutatedInPlace.addAll(tempSpace);
}
reorder(indices, listOne);
reorder(indices, listTwo);
推荐阅读
- ruby-on-rails - 使用 stabby lambda 调用 ruby 常量是否线程安全?
- angular - 如何比较 Angular 和 CSS 中的截止日期?
- angular - Angular ngBootstrap:使用下拉列表过滤表中的值
- r - 逻辑运算符 and, or 不工作
- javascript - TTS 上传到服务器后无法播放
- android - 我无法在android后台运行服务
- r - 这是创建箱线图的语法正确代码吗
- javascript - Discord.js 通过 ID 使用特定用户打开 DM 流
- c# - 如何使用 iframe 访问其他网站
- python - Django ORM:如何按日期排序,然后选择按外键分组的最佳对象?