Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does entrySet() in a LinkedHashMap also guarantee order?

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?

like image 222
Diego Avatar asked Jul 27 '09 19:07

Diego


People also ask

Is order maintained in LinkedHashMap?

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.

How does entrySet work?

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.

Is LinkedHashMap values ordered?

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.


2 Answers

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.

like image 62
Michael Myers Avatar answered Oct 08 '22 14:10

Michael Myers


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

like image 27
Daniel F. Thornton Avatar answered Oct 08 '22 14:10

Daniel F. Thornton