Andrew Mao
Andrew Mao

Reputation: 36910

Iteration order of LinkedHashMap collection views

After reading the documentation for LinkedHashMap (and having used it several times), I'm still not clear about one of its properties. Is the iteration order for a LinkedHashMap:

  1. the same as insertion order for entrySet(), keySet(), and values(), or
  2. the same as insertion order for entrySet() and keySet() but not values(), or
  3. only the same as insertion order for entrySet()?

I imagine the third scenario to be unlikely, but I would like to know if anyone knows if (1) or (2) is true since iteration over values() is probably a rare use case.

Upvotes: 12

Views: 7741

Answers (2)

M. Justin
M. Justin

Reputation: 21162

The Java 21 documentation for these methods in LinkedHashMap is more explicit about the ordering than in prior versions of Java. It makes it clear that all three collection view methods use the same order — the encounter order of the map.

  • entrySet: "The encounter order of the view matches the encounter order of entries of this map."
  • keySet: "The encounter order of the keys in the view matches the encounter order of mappings of this map."
  • values: "The encounter order of values in the view matches the encounter order of entries in this map."

The encounter order of a LinkedHashMap is insertion-order, unless the map was created as an access-order LinkedHashMap (using the special access-order constructor).

So as of Java 21, the answer is clearly documented that yes, entrySet, keySet, and values will return their elements in insertion order for a standard insertion-order LinkedHashMap.

Prior versions of Java did have the same behavior, but the documentation around it was less explicit.

Therefore, regardless of the version of Java, the order of these three methods are the same, and are (except for specific special access-order LinkedHashMap instances) in insertion order.

Upvotes: 0

fge
fge

Reputation: 121740

LinkedHashMap respects insertion order; so the first choice is the good.

A Map being a set of Map.Entry objects, options 2 and 3 would be rather strange ;)

Upvotes: 4

Related Questions