• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Ranch Hand
Posts: 558
2
Hibernate Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Create symphonies in seed and soil. For this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic