1

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?

M. Justin
22.7k12 gold badges131 silver badges167 bronze badges
asked Sep 27, 2013 at 19:04
1
  • This question is similar to: Iteration order of a LinkedHashMap. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Aug 28, 2024 at 2:49

2 Answers 2

3

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 the TreeMap 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.

answered Sep 27, 2013 at 19:07
2

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

answered Sep 27, 2013 at 19:06

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.