[英]Sort a List based on another List
我目前有一个String ID List<String>
( 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的最后一个值并存储它。 即日志的一个例子:
地图:1:巴黎,地图:2:巴黎,地图:3:巴黎
但我添加的是:
mapB.put("1", London);
mapB.put("2", Berlin);
mapB.put("3", Paris);
所以,是的,我对正在发生的事情感到有点困惑,是否有人可以提供一些指导? 谢谢!
这是因为你使用了两个fors。 因此,这在地图中添加了值:1 - 伦敦1 - 柏林1 - 巴黎2 - 伦敦2 - 柏林2 - 巴黎3 - 伦敦3 - 柏林3 - 巴黎
TreeMap只会记住您为每个索引输入的最后一个值,因此所有这些值都是巴黎。
如果你知道mIds和mCustomClass [相同长度]中有相应的元素,只需使用一个,只需使用mapB.put(mIds [i],mCustomClass [i])。
对于更通用的方法,如果在两个数组(或集合)中有相应的项,则应考虑创建一个更好的对象,有2个字段(id和class),只需为该对象编写自己的Comparator,帐户ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.