How to iterate a HashMap using the natural entrySet() order?

前端 未结 6 616
醉酒成梦
醉酒成梦 2021-01-02 13:12

My Map contains keys sorted in alphabetical order. When I display it, I\'m using entrySet().iterator(), but my results are not in the alphabetical order. How can I get my re

6条回答
  •  半阙折子戏
    2021-01-02 13:35

    No, your map does not hold elements in alphabetical order. You may have .put(..) then in that order, but the map does not have a defined iteration order.

    Others suggest using SortedSet, but you can also use LinkedHashMap. It guarantees iteration order:

    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

提交回复
热议问题