How can I sort Map values by key in Java?

Viewed 716719

I have a Map that has strings for both keys and values.

The data is like the following:

"question1", "1"
"question9", "1"
"question2", "4"
"question5", "2"

I want to sort the map based on its keys. So, in the end, I will have question1, question2, question3, and so on.

Eventually, I am trying to get two strings out of this Map:

  • First String: Questions (in order 1 .. 10)
  • Second String: Answers (in the same order as the question)

Right now I have the following:

Iterator it = paramMap.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry pairs = (Map.Entry) it.next();
    questionAnswers += pairs.getKey() + ",";
}

This gets me the questions in a string, but they are not in order.

17 Answers

Short answer

Use a TreeMap. This is precisely what it's for.

If this map is passed to you and you cannot determine the type, then you can do the following:

SortedSet<String> keys = new TreeSet<>(map.keySet());
for (String key : keys) { 
   String value = map.get(key);
   // do something
}

This will iterate across the map in natural order of the keys.


Longer answer

Technically, you can use anything that implements SortedMap, but except for rare cases this amounts to TreeMap, just as using a Map implementation typically amounts to HashMap.

For cases where your keys are a complex type that doesn't implement Comparable or you don't want to use the natural order then TreeMap and TreeSet have additional constructors that let you pass in a Comparator:

// placed inline for the demonstration, but doesn't have to be a lambda expression
Comparator<Foo> comparator = (Foo o1, Foo o2) -> {
        ...
    }

SortedSet<Foo> keys = new TreeSet<>(comparator);
keys.addAll(map.keySet());

Remember when using a TreeMap or TreeSet that it will have different performance characteristics than HashMap or HashSet. Roughly speaking operations that find or insert an element will go from O(1) to O(Log(N)).

In a HashMap, moving from 1000 items to 10,000 doesn't really affect your time to lookup an element, but for a TreeMap the lookup time will be about 1.3 times slower (assuming Log2). Moving from 1000 to 100,000 will be about 1.6 times slower for every element lookup.

Assuming TreeMap is not good for you (and assuming you can't use generics):

List sortedKeys=new ArrayList(yourMap.keySet());
Collections.sort(sortedKeys);
// Do what you need with sortedKeys.

Using Java 8:

Map<String, Integer> sortedMap = unsortMap.entrySet().stream()
            .sorted(Map.Entry.comparingByKey())
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                    (oldValue, newValue) -> oldValue, LinkedHashMap::new));

Just in case you don't want to use a TreeMap:

public static Map<Integer, Integer> sortByKey(Map<Integer, Integer> map) {
    List<Map.Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet());
    list.sort(Comparator.comparingInt(Map.Entry::getKey));
    Map<Integer, Integer> sortedMap = new LinkedHashMap<>();
    list.forEach(e -> sortedMap.put(e.getKey(), e.getValue()));
    return sortedMap;
}

Also, in case you wanted to sort your map on the basis of values, just change Map.Entry::getKey to Map.Entry::getValue.

In Java 8 you can also use .stream().sorted():

myMap.keySet().stream().sorted().forEach(key -> {
        String value = myMap.get(key);

        System.out.println("key: " + key);
        System.out.println("value: " + value);
    }
);

A good solution is provided here. We have a HashMap that stores values in unspecified order. We define an auxiliary TreeMap and we copy all data from HashMap into TreeMap using the putAll method. The resulting entries in the TreeMap are in the key-order.

Use LinkedHashMap, which provides the key ordering. It's also gives the same performance as HashMap. They both implement the Map interface, so you can just replace the initialization object HashMap to LinkedHashMap.

Use the below tree map:

Map<String, String> sortedMap = new TreeMap<>(Comparator.comparingInt(String::length)
    .thenComparing(Function.identity()));

Whatever you put in this sortedMap, it will be sorted automatically. First of all, TreeMap is sorted implementation of Map Interface.

There is a but as it sorts keys in the natural order fashion. As the Java documentation says, String type is a lexicographic natural order type. Imagine the below list of numbers with the String type. It means the below list will not be sorted as expected.

List<String> notSortedList = List.of("78","0", "24", "39", "4","53","32");

If you just use the default TreeMap constructor like below and push each element one-by-one like below:

Map<String, String> map = new TreeMap<>();
for (String s : notSortedList) {
    map.put(s, s);
}

System.out.println(map);

The output is: {0=0, 14=14, 24=24, 32=32, 39=39, 4=4, 48=48, 53=53, 54=54, 78=78}

As you see, number 4, for example, comes after '39'. This is the nature of the lexicographic data types, like String. If that one was an Integer data type then that was okay though.

To fix this, use an argument to first check the length of the String and then compare them. In Java 8 it is done like this:

Map<String, String> sortedMap = new TreeMap<>(Comparator.comparingInt(String::length)
    .thenComparing(Function.identity()));

It first compares each element by length then apply check by compareTo as the input the same as the element to compare with.

If you prefer to use a more understandable method, the above code will be equivalent with the below code:

Map<String, String> sortedMap = new TreeMap<>( new Comparator() { @Override public int compare(String o1, String o2) { int lengthDifference = o1.length() - o2.length(); if (lengthDifference != 0) return lengthDifference; return o1.compareTo(o2); } } );

Because the TreeMap constructor accepts the comparator Interface, you can build up any an even more complex implementation of Composite classes.

This is also another form for a simpler version.

Map<String,String> sortedMap = new TreeMap<>(
   (Comparator<String>) (o1, o2) ->
    {
        int lengthDifference = o1.length() - o2.length();
        if (lengthDifference != 0)
            return lengthDifference;
        return o1.compareTo(o2);
    }
);
Related