问题
One can iterate through a SortedMap by using the iterator from myMap.entrySet().iterator()
. But does this iterator preserve the ordering of the sorted map object ?
The SortedMap interface has no own methods to iterate through the entries. What is the standard way to iterate ordered through the entries ?
回答1:
The standard iterator is guaranteed to keep the iteration order exactly the same as the natural order of the keys, for both keys and entries. This is stated in the documentation and can be easily tested.
On the other hand, if you're interested in preserving iteration order over keys and entries in the same order that the keys were inserted, then you're looking for a LinkedHashMap.
来源:https://stackoverflow.com/questions/14085906/how-to-iterate-through-a-sortedmap-with-same-ordering