Reputation: 3036
Hi I had a requirement where objects of a map are to arranged in order of keys of another map. here is the map
Map ObjectMap = new HashMap()
ObjectMap .put(id1,Obj1);
ObjectMap .put(id2,Obj2);
ObjectMap .put(id3,Obj3);
ObjectMap .put(id4,Obj4);
Now a rank map decides the order of ids in ObjectMap
Map rankedMap = new HashMap()
rankedMap .put(rank1,id3);
rankedMap .put(rank2,id4);
rankedMap .put(rank3,id1);
rankedMap .put(rank4,id2);
Now I have to arrange the ObjectMap objects accoding to the rank of each ids like
ObjectMap .put(id3,Obj1);
ObjectMap .put(id4,Obj2);
ObjectMap .put(id1,Obj3);
ObjectMap .put(id2,Obj4);
ids
are Long
objects
ranks
are int
objects
Please help Thanks in advance
Upvotes: 1
Views: 1633
Reputation: 19682
The 'rankedMap' should be a linked map, as said above:
Map rankedMap = new LinkedHashMap()
rankedMap .put(rank1,id3);
rankedMap .put(rank2,id4);
rankedMap .put(rank3,id1);
rankedMap .put(rank4,id2);
next, you can iterate over the ids in the rankedMap to fill the rankedObjectMap, which is also a linkedHashMap: (code not tested)
Map rankedObjectMap = new LinkedHashMap();
for(Object id : rankedMap.values()){
rankedObjectMap.put(id, objectMap.get(id));
}
Upvotes: 2
Reputation: 178471
HashMap
has no defined ordering. If you want ordering, and still benefit the O(1) seek time the HashMap
offers, you might want to use LinkedHashMap, but note that ordering in this map is defined by order of insertions. You will have to take care of it by inserting your elements in order.
Upvotes: 1