Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is the Java HashMap keySet() iteration order consistent?

I understand that the Set returned from a Map's keySet() method does not guarantee any particular order.

My question is, does it guarantee the same order over multiple iterations. For example

Map<K,V> map = getMap();  for( K k : map.keySet() ) { }  ...  for( K k : map.keySet() ) { } 

In the above code, assuming that the map is not modified, will the iteration over the keySets be in the same order. Using Sun's jdk15 it does iterate in the same order, but before I depend on this behavior, I'd like to know if all JDKs will do the same.

EDIT

I see from the answers that I cannot depend on it. Too bad. I was hoping to get away with not having to build some new Collection to guarantee my ordering. My code needed to iterate through, do some logic, and then iterate through again with the same ordering. I'll just create a new ArrayList from the keySet which will guarantee order.

like image 914
karoberts Avatar asked Dec 10 '09 17:12

karoberts


People also ask

Is keySet of HashMap ordered?

As we know that Hash map in Java does not maintain insertion order either by key or by order. Also it does not maintain any other order while adding entries to it.

Is keySet ordered Java?

It doesn't have to be. A map's keySet function returns a Set and the set's iterator method says this in its documentation: "Returns an iterator over the elements in this set. The elements are returned in no particular order (unless this set is an instance of some class that provides a guarantee)."

Is HashMap maintain order?

HashMap does not maintains insertion order in java. Hashtable does not maintains insertion order in java. LinkedHashMap maintains insertion order in java.

What does HashMap keySet do in Java?

HashMap. keySet() method in Java is used to create a set out of the key elements contained in the hash map. It basically returns a set view of the keys or we can create a new set and store the key elements in them. Parameters: The method does not take any parameter.


Video Answer


2 Answers

You can use a LinkedHashMap if you want a HashMap whose iteration order does not change.

Moreover you should always use it if you iterate through the collection. Iterating over HashMap's entrySet or keySet is much slower than over LinkedHashMap's.

like image 174
ciamej Avatar answered Sep 18 '22 18:09

ciamej


If it is not stated to be guaranteed in the API documentation, then you shouldn't depend on it. The behavior might even change from one release of the JDK to the next, even from the same vendor's JDK.

You could easily get the set and then just sort it yourself, right?

like image 30
Ken Liu Avatar answered Sep 20 '22 18:09

Ken Liu