Reputation: 5212
I can't confirm this in the documentation but if I have a LinkedHashMap
and I call keySet()
on it and iterate over this set is it guaranteed to iterate in insertion order?
Upvotes: 1
Views: 558
Reputation: 213243
It's specified in the Map
documentation:
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 theTreeMap
class, make specific guarantees as to their order; others, like the HashMap class, do not.
That means for LinkedHashMap
, all the 3 methods - values()
, keySet()
and entrySet()
, each of them providing 3 different collection views, are guaranteed to iterate in the insertion order.
Upvotes: 3
Reputation: 6452
Yes. See the docs(that you can not see) here: http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html
Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)
Upvotes: 2