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?
LinkedHashMap maintains the order of insertion. So while iterating over its keys, the elements are returned in the order they were inserted. LinkedHashMap uses a doubly-linked list to maintain the order of insertion. If a key is reinserted, its insertion order is not affected.
entrySet() method in Java is used to create a set out of the same elements contained in the hash map. It basically returns a set view of the hash map or we can create a new set and store the map elements into them. Parameters: The method does not take any parameter.
The whole purpose of the LinkedHashMap class is to keep the ordering of the elements while iterating the map and this behavior is well specified.
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.
If you're sure no changes will be made during the iteration, then proper ordering with entrySet()
is guaranteed, as stated in the API.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With