How can I sort map keys in Java?

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

+42
java
Feb 20 '09 at 21:57
source share
3 answers

Use TreeMap , which is an implementation of the SortedMap interface. He presents his keys in sorted order.

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

If you are working with another map implementation that is not sorted as you see fit, you can pass it to the TreeMap constructor to create a new map with sorted keys.

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

A TreeMap works with any type of key that implements the Comparable interface, placing them in its β€œnatural” order. For keys that are not Comparable , or whose natural order is not what you need, you can implement your own Comparator and specify what is in the constructor.

+64
Feb 20 '09 at 21:59
source share

You have several options. Listed in order of preference:

  • Use SortedMap :
    SortedMap<whatever> myNewMap = new TreeMap<whatever>(myOldMap);
    This is much preferable if you want to repeat several times. It keeps the keys sorted, so you don't need to sort them before iterating.
  • No # 2.
  • No and # 3.
  • SortedSet<whatever> keys = new TreeSet<whatever>(myMap.keySet());
  • List<whatever> keys = new ArrayList<whatever>(myMap.keySet()); Collections.sort(keys);

The last two will get what you want, but should only be used if you want iteration only once, then forget it all.

+28
Feb 20 '09 at 22:04
source share

You can create a sorted collection on repeat, but it makes sense to have a sorted map first. (As already suggested)

Anyway, this is how you do it.

 Map<String, Object> map; for(String key: new TreeSet<String>(map.keySet()) { // accessed in sorted order. } 
+8
Feb 20 '09 at 22:07
source share



All Articles