简体   繁体   English

基于另一个列表对列表进行排序

[英]Sort a List based on another List

I currently have an ordered list of String ids ( List<String> ) and an unordered list of a custom class ( List<CustomClass> ). 我目前有一个String ID List<String>List<String> )和一个自定义类( List<CustomClass> )的无序列表。 I'd like to order the list of custom class objects based on the ordered list of IDS. 我想根据IDS的有序列表来定制自定义类对象的列表。

I got the impression the best way to do this is use a TreeMap. 我得到的印象是,最好的方法是使用TreeMap。 So I implemented this: 所以我实现了这个:

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);

Although, it stores all the ids fine, but when I print out the TreeMap, it seems as if it only takes the last Value of mapB and stores that. 虽然,它可以很好地存储所有ID,但是当我打印出TreeMap时,似乎它只需要mapB的最后一个值并存储它。 Ie an example of logs: 即日志的一个例子:

Map: 1 : Paris, Map: 2 : Paris, Map: 3 : Paris 地图:1:巴黎,地图:2:巴黎,地图:3:巴黎

But what I added was: 但我添加的是:

mapB.put("1", London);
mapB.put("2", Berlin);
mapB.put("3", Paris);

So yeah, I'm a little confused to what's happening, could anyone provide some guidance? 所以,是的,我对正在发生的事情感到有点困惑,是否有人可以提供一些指导? Thanks! 谢谢!

it's because you are using two fors. 这是因为你使用了两个fors。 Thus, this adds in the map the values: 1 - London 1 - Berlin 1 - Paris 2 - London 2 - Berlin 2 - Paris 3 - London 3 - Berlin 3 - Paris 因此,这在地图中添加了值:1 - 伦敦1 - 柏林1 - 巴黎2 - 伦敦2 - 柏林2 - 巴黎3 - 伦敦3 - 柏林3 - 巴黎

The TreeMap only remembers the last value you put in for each index, therefor Paris for all of them. TreeMap只会记住您为每个索引输入的最后一个值,因此所有这些值都是巴黎。

If you know you have corresponding elements in mIds and mCustomClass [same length], just use one for and simply use mapB.put(mIds[i], mCustomClass[i]). 如果你知道mIds和mCustomClass [相同长度]中有相应的元素,只需使用一个,只需使用mapB.put(mIds [i],mCustomClass [i])。

For a more general approach, if you have corresponding items in the two arrays (or collections), you should consider creating a better object, having 2 fields (id and class) and simply write your own Comparator for that object, that only takes into account the ID. 对于更通用的方法,如果在两个数组(或集合)中有相应的项,则应考虑创建一个更好的对象,有2个字段(id和class),只需为该对象编写自己的Comparator,帐户ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM