How to iterate a HashMap using the natural entrySet() order?
我的地图包含按字母顺序排序的键。 当我显示它时,我正在使用entrySet()。iterator(),但我的结果不是按字母顺序排列。
如何才能按顺序获得结果?
不,您的地图不按字母顺序保存元素。您可能按此顺序拥有
其他人建议使用
This implementation (LinkedHashMap) spares its clients from the unspecified, generally chaotic ordering provided by HashMap (and Hashtable), without incurring the increased cost associated with TreeMap
使用TreeMap:
A Red-Black tree based
NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by aComparator provided at map creation time, depending on which constructor is used...
您可以使用ConcurrentSkipListMap或TreeMap。
由于
另一方面,
My Map contains keys sorted in alphabetical order
这不是真的。
使用http://download.oracle.com/javase/6/docs/api/java/util/SortedMap.html或在迭代前对键进行排序