hashmap keyset automatically sorted
13,860
Solution 1
HashMap makes absolutely no guarantees about the iteration order. It can (and will) even change completely when new elements are added.
LinkedHashMap will iterate in the order in which the entries were put into the map
Solution 2
The order in which you see the entries in the HashMap
depends on the hash codes of the keys and order of the entries in the bucket I believe and it is implementation dependent, but don't rely on HashMap
for ordering at all. Whereas LinkedHashMap
and TreeMap
do guarantee a certain order.
![Jochem Gruter](https://i.stack.imgur.com/CGdfG.jpg?s=256&g=1)
Author by
Jochem Gruter
Updated on July 22, 2022Comments
-
Jochem Gruter almost 2 years
HashMap<String, String[]> content = new HashMap<String, String[]>(); content.put("Help", new String[]{"About"}); content.put("View", new String[]{"Grid"}); content.put("File", new String[]{"Import", "Export"}); for(String key : content.keySet()){ System.out.println(key); }
The above code logs:
View Help File
But why is this sorted?