java - Java 集合:根据单独的键列表对值列表进行排序
问题描述
我有两个清单。键列表中的每个键对应于值列表中的一个值。假设这两个列表大小相同。我需要根据键列表对两个列表进行排序。
我尝试了以下方法,但显然它不起作用,因为它会弄乱键值关联。除了编写自己的排序实现之外,我只是不知道还能做什么。
// Would mess up the key-value associations
public void sort() {
Collections.sort(this.keys);
Collections.sort(this.values);
}
/* Example:
this.keys = (2, 1, 4)
this.values = ("value for 2", "value for 1", "value for 4")
this.sort()
this.keys = (1, 2, 4)
this.values = ("value for 1", "value for 2", "value for 4") */
有没有一种简单的方法可以做到这一点?我宁愿坚持使用内置的排序功能,而不是自己编写。我也不能改变底层的数据结构。
解决方案
如果如您所说,您需要保留两个列表,则可以尝试以下操作:
// Create a map that orders its data.
Map<Integer, String> tmp = new TreeMap<>();
// Put your data into this structure and let it sort the data for you.
for (int i=0; i<keys.size(); i++) {
tmp.put(keys.get(i), values.get(i));
}
// Clear your original lists.
keys.clear()
values.clear();
// Put the data back into your lists - but sorted this time.
for (Integer key : tmp.keySet()) {
keys.add(key);
values.add(tmp.get(key));
}
推荐阅读
- xamarin - Xamarin.Auth 是否可以通过服务器端访问令牌检索支持授权代码流,如果不支持,为什么不支持/什么可以?
- angular - 如何增加 Ionic4 中警报组件的宽度?
- javascript - 如何在 angularjs 中格式化 data.message?
- c# - 如何调用对象的方法?
- java - 如何将循环中的阻塞调用更改为 Java 中的异步调用
- c - 创建一个大小固定的 unsigned short int * 变量(没有 malloc)
- c# - 如何检查设备是否具有生物识别功能
- pyspark - 如何通过 Pyspark 中同一数据框中另一列的正则表达式值过滤数据框中的一列
- powershell - PowerShell,查找重复文件夹的更有效方法
- json - 在 TypeScript 中获取 JSON 数组的最后一个元素