• Post Reply Bookmark Topic Watch Topic
  • New Topic

Does LinkedHashMap.values() returns a Collection of values which were in same order as inserted?  RSS feed

 
Kumar Raja
Ranch Hand
Posts: 550
2
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Hi All,

I have a very basic question on ordering of the values, returned by LinkedHashMap.values() method.

A little background. I have a method which processes several records from Database and inserts them into a Map as Key/Value pairs. The database returns the records as per ORDER BY clause and I want to retain the same order as returned by Database. So, I chose LinkedHashMap, as it stores the records in Insertion Order and the original order will not change, if the key is reinserted.

Now I have this Map, out of which I'm interested in only values part (Keys are not required at this point). I need to return the values collection from this Map, for some iteration over it (need to write to some other location in the same order as returned by database). I thought of using values() method of this LinkedHashMap and wanted to understand, if this method returns the values into Collection, in the same order, the records were originally inserted into map.

If the order is not guaranteed even with the usage of LinkedHashMap, what is the other alternative I can choose. The fallback option is to iterate over the Map and explicity writing them to another ordered collection. But just wondering, if there is already such provision.


Thanks
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, any iteration on a LinkedHashMap's keys, values, or entries will match insertion order, unless you explicitly tell it at construction time to use access order instead.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!