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

前端 未结 6 586
醉酒成梦
醉酒成梦 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:18

    Use TreeMap:

    A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used...

    0 讨论(0)
  • 2021-01-02 13:26

    My Map contains keys sorted in alphabetical order

    This is not true.

    Use http://download.oracle.com/javase/6/docs/api/java/util/SortedMap.html or sort your keys before iterate

    0 讨论(0)
  • 2021-01-02 13:32

    Since HashMap uses hashing to store the entries in an underlying container, you aren't guaranteed any specific order. If you want your entries from your HashMap ordered, you must sort them yourself.

    A TreeMap on the other hand will maintain some sort of order (you can dictate that yourself by implementing the Comparable interface), so if you get its entry set, it will come to you alphabetically. String already implements Comparable, so they will be returned to you in alphabetical order.

    0 讨论(0)
  • 2021-01-02 13:32

    You can use ConcurrentSkipListMap or TreeMap.

    0 讨论(0)
  • 2021-01-02 13:33

    For anyone finding this question in 2020 and beyond...
    Now that we have streams, you can do something like this:

    map.entrySet()
      .stream()
      .sorted(Map.Entry.comparingByKey())
      .forEach(System.out::println);
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题