我目前有一个字符串 ID 的有序列表 (List<String>
) 和一个自定义类的无序列表 (List<CustomClass>
)。我想根据 IDS 的有序列表对自定义类对象列表进行排序。
我的印象是最好的方法是使用 TreeMap。所以我实现了这个:
Map<String, CustomClass> mapB = new HashMap<String, CustomClass>();
for (String id : mIds) {
for (CustomClass customClass : mCustomClass) {
mapB.put(thingId, mCustomClass);
}
}
Map<String, CustomClass> treeMap = new TreeMap<String, CustomClass>();
treeMap.putAll(mapB);
尽管它可以很好地存储所有 id,但是当我打印出 TreeMap 时,它似乎只获取 mapB 的最后一个值并存储它。 IE。日志示例:
Map: 1 : Paris, Map: 2 : Paris, Map: 3 : Paris
但是我添加的是:
mapB.put("1", London);
mapB.put("2", Berlin);
mapB.put("3", Paris);
是的,我对发生的事情有点困惑,有人可以提供一些指导吗?谢谢!
最佳答案
因为你用了两个for。因此,这会在 map 中添加以下值: 1 - 伦敦 1 - 柏林 1 - 巴黎 2 - 伦敦 2 - 柏林 2 - 巴黎 3 - 伦敦 3 - 柏林 3 - 巴黎
TreeMap 只记住您为每个索引输入的最后一个值,因此所有索引都是巴黎。
如果您知道 mIds 和 mCustomClass [相同长度] 中有对应的元素,只需使用一个 for 并简单地使用 mapB.put(mIds[i], mCustomClass[i])。
对于更通用的方法,如果你在两个数组(或集合)中有相应的项目,你应该考虑创建一个更好的对象,有 2 个字段(id 和 class)并简单地为该对象编写你自己的比较器,即仅考虑 ID。
关于java - 根据另一个列表对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26778969/