How to Sort HashMap according to keys

This article is going to very interesting as we will explore several different ways on how to sort a HashMap using keys.

1. Introduction

Usually if we are expecting the sorted keys in Map we would use some kind of SortedMap. For this article the assumption is that we have a HashMap but now we want to sort the keys.

If you are looking for comparingByKey and comparingByValue methods added in Map.Entry interface click here.

2. Content

Let’s assume that we have below Map values as input:

Map<String, Integer> map = new HashMap<>();
map.put("Sansa", 12);
map.put("Arya", 16);
map.put("Jon", 19);
map.put("Robb", 23);
map.put("Bran", 9);
map.put("Rickon", 5);
 
key = Sansa : Value = 12
key = Bran : Value = 9
key = Arya : Value = 16
key = Jon : Value = 19
key = Robb : Value = 23
key = Rickon : Value = 5

3. Sort Map using TreeMap constructor

Alright, first way to sort the keys in Map is to use the TreeMap implementation. Just create a new instance of TreeMap using unsorted map as a constructor parameter. This will work if all the keys in unsorted map are mutually comparable that means the keys can be compared as k1.compareTo(k2). In our example we are using String as a key which implements Comparable interface and hence is mutually comparable.

Map<String, Integer> sortedMap = new TreeMap<>(map);

key = Arya : Value = 16
key = Bran : Value = 9
key = Jon : Value = 19
key = Rickon : Value = 5
key = Robb : Value = 23
key = Sansa : Value = 12

4. Sort Map using TreeMap putAll method

The second way to sort the keys is using the putAll method of TreeMap class. putAll method accepts the Map as input. putAll method copies all the mappings from specified Map to TreeMap.

Map<String, Integer> sortedMap = new TreeMap<>();
sortedMap.putAll(map);

key = Arya : Value = 16
key = Bran : Value = 9
key = Jon : Value = 19
key = Rickon : Value = 5
key = Robb : Value = 23
key = Sansa : Value = 12

5. Sort using ArrayList and Collections.sort

The third way is to copy all the keys into the List, sort the List and put all the sorted keys in LinkedHashMap as it maintains the order of insertion.

Map<String, Integer> inputMap = inputMap();
List<String> keys = new ArrayList<>(map);
Collections.sort(keys);

Map<String, Integer> sortedMap = new LinkedHashMap<>();
for (String key : keys) {
	sortedMap.put(key, inputMap.get(key));
}

key = Arya : Value = 16
key = Bran : Value = 9
key = Jon : Value = 19
key = Rickon : Value = 5
key = Robb : Value = 23
key = Sansa : Value = 12

6. Sort using Comparator

Now this is very interesting way to sort keys. Using Comparator can be bit of a pain but let’s try to implement a generic way to sort the keys in Map. Below is the generic code to sort the keys using Comparator.

public <K extends Comparable<? super K>, V> 
Map<K, V> sortByKey(Map<K, V> map) {

	List<Map.Entry<K, V>> list = new ArrayList<Map.Entry<K, V>>(map.entrySet());

	Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
		@Override
		public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
			return o1.getKey().compareTo(o2.getKey());
		}
	});

	Map<K, V> result = new LinkedHashMap<>();
	for (Map.Entry<K, V> entry : list) {
		result.put(entry.getKey(), entry.getValue());
	}

	return result;
}

7. Conclusion

In this article, we saw how to sort the Map using key in 4 different ways i.e. using TreeMap constructor, using TreeMap class’s method putAll, using ArrayList and Collections.sort() method and using Comparator.

Leave a Reply

Your email address will not be published. Required fields are marked *