Does Java's LinkedHashMap maintain the order of keys?

Armand picture Armand · Aug 13, 2010 · Viewed 42.5k times · Source

When LinkedHashMap.keySet() is called, will the order of the Set returned be the same as the order the keys were added in?

Answer

Tom Tresansky picture Tom Tresansky · Aug 13, 2010

Yes.

See: LinkedHashMap:

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

and from the HashMap#keySet documentation:

The set [returned] is backed by the map, so changes to the map are reflected in the set, and vice-versa.