How can I sort the keys of a Map in Java?

后端 未结 4 1084
清歌不尽
清歌不尽 2020-12-13 12:40

This is a very basic question, I\'m just not that good with Java. I have a Map and I want to get a list or something of the keys in sorted order so I can iterate over them.

4条回答
  •  再見小時候
    2020-12-13 12:55

    Use a TreeMap, which is an implementation of the SortedMap interface. It presents its keys in sorted order.

    Map map = new TreeMap();
    /* Add entries to the map in any order. */
    ...
    /* Now, iterate over the map's contents, sorted by key. */
    for (Map.Entry entry : map.entrySet()) {
      System.out.println(entry.getKey() + ": " + entry.getValue());
    }
    

    If you are working with another Map implementation that isn't sorted as you like, you can pass it to the constructor of TreeMap to create a new map with sorted keys.

    void process(Map original) {
      Map copy = new TreeMap(original);
      /* Now use "copy", which will have keys in sorted order. */
      ... 
    }
    

    A TreeMap works with any type of key that implements the Comparable interface, putting them in their "natural" order. For keys that aren't Comparable, or whose natural ordering isn't what you need, you can implement your own Comparator and specify that in the constructor.

提交回复
热议问题