javaiterationlinkedhashmap

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


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?


Solution

  • 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.