• Post Reply Bookmark Topic Watch Topic
  • New Topic

ordering data in a map  RSS feed

 
Priya Rangan
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all,
I have some data in (name, value) pairs that i would like to store in a map. I would like them to be sorted in the order in which i put the values in the map. For example if i have:
resultMap.put( q, "3" );
resultMap.put( b, "4" );
resultMap.put( a, "1" );
So, if i iterate over the keys or values of i map, i would like to retrieve them in the same order as i put them in the map( that is: q,b,a )
How can i impose this order?
Thanks very much in advance...
Priya
 
le taylom
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why don't you try using a child interface of Map, i.e. SortedMap, and use the controls that it gives you on ordering?
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since JDK1.4, there is LinkedHashMap for exactly this use.
 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi le taylom,
can u throw more light on a thought u suggested?
i've not really used Collections so much so i don't know how to achieve what u suggested.
also, i have some other solution in mind,
- if we have the Key as some Object then we can probably embed Date field in the Key Object, which refers to the creation date (with time) of the object.
- then we can have hashCode() method override in to return the 'long' number corresponding to date and then have Comparator that is sorting by this date. (or may b if we don't override the hashCode() it would be fine).
here, the assumption is- "all the Keys are inserted into the HashMap or anything in the order they are created", which might not be true all the time but i guess this is a possible solution.
of course, if we use JDK1.4 then solution suggested by Ilja Preuss would work and we better use that one but i was just trying to override the comparision done by the Map interface while entering the objects using the Key. please throw some light on what i am trying to do. i just want to explore possibilities.
regards,
maulin
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!