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

后端 未结 4 1078
清歌不尽
清歌不尽 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:49

    You have several options. Listed in order of preference:

    1. Use a SortedMap:
      SortedMap myNewMap = new TreeMap(myOldMap);
      This is vastly preferable if you want to iterate more than once. It keeps the keys sorted so you don't have to sort them before iterating.
    2. There is no #2.
    3. There is no #3, either.
    4. SortedSet keys = new TreeSet(myMap.keySet());
    5. List keys = new ArrayList(myMap.keySet()); Collections.sort(keys);

    The last two will get you what you want, but should only be used if you only want to iterate once and then forget the whole thing.

提交回复
热议问题