John Threepwood
John Threepwood

Reputation: 16143

How to iterate through a SortedMap with same ordering?

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 ?

Upvotes: 3

Views: 8475

Answers (1)

Óscar López
Óscar López

Reputation: 236064

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.

Upvotes: 7

Related Questions