Is the order guaranteed for the return of keys and values from a LinkedHashMap object?

user256239 picture user256239 · May 27, 2010 · Viewed 47.1k times · Source

I know LinkedHashMap has a predictable iteration order (insertion order). Does the Set returned by LinkedHashMap.keySet() and the Collection returned by LinkedHashMap.values() also maintain this order?

Answer

Powerlord picture Powerlord · May 27, 2010

The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not.

-- Map

This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

-- LinkedHashMap

So, yes, keySet(), values(), and entrySet() (the three collection views mentioned) return values in the order the internal linked list uses. And yes, the JavaDoc for Map and LinkedHashMap guarantee it.

That is the point of this class, after all.