I currently have an ordered list of String ids (List<String>
) and an unordered list of a custom class (List<CustomClass>
). I'd like to order the list of custom class objects based on the ordered list of IDS.
I got the impression the best way to do this is use a 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. I.e. an example of logs:
Map: 1 : Paris, Map: 2 : Paris, Map: 3 : Paris
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. 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
The TreeMap only remembers the last value you put in for each index, therefor Paris for all of them.
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]).
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.