How to iterate through a SortedMap with same ordering?

橙三吉。 提交于 2020-07-21 03:26:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!