4

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!

Andre Perkins
  • 7,640
  • 6
  • 25
  • 39
Connor McFadden
  • 441
  • 1
  • 4
  • 20
  • Are strings in List present in anyway in CustomClass? – SMA Nov 06 '14 at 12:05
  • The id is being accessed from the model in this class, but it's not being stored as local variable or anything. – Connor McFadden Nov 06 '14 at 12:06
  • Please provide relation between List and List and also implementation of CustomeClass. And if any field in CustomClass corresponds to any of the items present in List – SMA Nov 06 '14 at 12:07
  • possible duplicate of [In Java how do you sort one list based on another?](http://stackoverflow.com/questions/18129807/in-java-how-do-you-sort-one-list-based-on-another) – SpaceTrucker Nov 06 '14 at 12:25

1 Answers1

3

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.

Adrian B.
  • 1,592
  • 1
  • 20
  • 38