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

Java

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

Use a TreeMap, which is an implementation of the SortedMap interface. It presents its 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's 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 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<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, 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.

Solution 2 - Java

You have several options. Listed in order of preference:

  1. Use a SortedMap:
    SortedMap<whatever> myNewMap = new TreeMap<whatever>(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<whatever> keys = new TreeSet<whatever>(myMap.keySet());
  5. List<whatever> keys = new ArrayList<whatever>(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.

Solution 3 - Java

You can create a sorted collection when iterating but it make more sense to have a sorted map in the first place. (As has already been suggested)

All the same, here is how you do it.

Map<String, Object> map;
for(String key: new TreeSet<String>(map.keySet()) {
  // accessed in sorted order.
}

Solution 4 - Java

Apart from the methods mentioned in other answers, with Java 8 streams, another shorthand to get a sorted key list from a map would be -

List<T> sortedKeys = myMap.keySet().stream().sorted().collect(Collectors.toList());

One could actually get stuff done after .sorted() as well (like using a .map(...) or a .forEach(...)), instead of collecting it in the list and then iterating over the list.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBialeckiView Question on Stackoverflow
Solution 1 - JavaericksonView Answer on Stackoverflow
Solution 2 - JavaMichael MyersView Answer on Stackoverflow
Solution 3 - JavaPeter LawreyView Answer on Stackoverflow
Solution 4 - JavaShreyasView Answer on Stackoverflow