How to iterate through a SortedMap with same ordering?

John Threepwood picture John Threepwood · Dec 29, 2012 · Viewed 7.7k times · Source

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 ?

Answer

Óscar López picture Óscar López · Dec 29, 2012

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.