Does entrySet() in a LinkedHashMap also guarantee order?

JavaLinkedhashmap

Java Problem Overview


I am using a linkedHashMap to guarantee order when someone tries to access it. However, when it comes time to iterate over it, does using entrySet() to return key/value pairs guarantee order as well? No changes will be made while iterating.

EDIT: Also, are there any adverse effects from iterating through the map by iterating through its keys and calling get?

Java Solutions


Solution 1 - Java

According to the Javadocs, yes.

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

As for the edit, no, it should work just fine. But the entry set is somewhat faster since it avoids the overhead of looking up every key in the map during iteration.

Solution 2 - Java

If you're sure no changes will be made during the iteration, then proper ordering with entrySet() is guaranteed, as stated in the API.

Solution 3 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDiegoView Question on Stackoverflow
Solution 1 - JavaMichael MyersView Answer on Stackoverflow
Solution 2 - JavaDaniel F. ThorntonView Answer on Stackoverflow
Solution 3 - JavaRobertView Answer on Stackoverflow