1

Let's say I have a LinkedHashMap<String, Double> myMap which I added pair1, pair2, pair3 pairs to.

And now I do the following loop :

for (Double currDouble : myMap.getValues()) {...}

Would the First Double object in the loop be the one of pair1? And second of pair2? Or it doesn't have to be?

I checked with similar program and It seems that it does keep insertion order, but Would that always be the case?

nadavgam
  • 2,014
  • 5
  • 20
  • 48

3 Answers3

3

By default the LinkedHashMap preserves the insertion order. Though there is an option to switch over to access order which might have been the confusing factor.

So to answer your question, yes, the first Double will be from pair1 and the second from pair2 etc. Given the fact that you didn't set the LinkedHashMap to access order.

If you are still not sure about the behavior, you can always test it by adding a bunch of data to a LinkedHashMap, and iterate over it like you described in your question. You'll see that it will preserve insertion order (or access order if set).

Vladimir Vagaytsev
  • 2,871
  • 9
  • 33
  • 36
n247s
  • 1,898
  • 1
  • 12
  • 30
2

Yes!

From the first sentence of the LinkedHashMap documentation: ... implementation of the Map interface, with predictable iteration order.... which is normally the order in which keys were inserted into the map (insertion-order).

If a key is reinserted ( possibly with a different value ) it doesn't change the original order.

Gonen I
  • 5,576
  • 1
  • 29
  • 60
0

See Java Class that implements Map and keeps insertion order?

You could just do:

for (String key : myMap.getKeys())
  Double d = myMap.get(key);
Community
  • 1
  • 1
nijave
  • 489
  • 5
  • 11