• 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 ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Paul Clapham
  • Devaka Cooray
  • Ron McLeod
  • paul wheaton
Saloon Keepers:
  • Tim Moores
  • Piet Souris
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Al Hobbs
  • Frits Walraven
  • Scott Selikoff

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

Ranch Hand
Posts: 558
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.

Posts: 6109
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.
I didn't say it. I'm just telling you what this tiny ad said.
the value of filler advertising in 2021
    Bookmark Topic Watch Topic
  • New Topic