Sort Map by Key in Java
Tags: Map TreeMap Comparator
In this Java core tutorial, we show you how to implement the Java method to sort elements of a Map object by its entry key in the Java program.
Implement method to sort a map by key
Firstly, create a new class named MapUtils and implement a method sortMapByKey() which expects a Map as argument and returns a sorted Map.
MapUtils.java
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
public class MapUtils {
public static Map<String, String> sortMapByKey(Map<String, String> map) {
if(map == null) {
return null;
}
Map<String, String> sortedMap = new TreeMap<>(new Comparator<String>() {
@Override
public int compare(String key1, String key2) {
return key1.compareTo(key2);
}
});
sortedMap.putAll(map);
return sortedMap;
}
}
Using MapUtils.sortMapByKey() method to sort map
In the following example Java program we use the MapUtils.sortMapByKey() static method above to sort a map.
SortMapByKeyExample.java
import java.util.HashMap;
import java.util.Map;
public class SortMapByKeyExample {
public static void main(String[] args) {
Map<String, String> sampleMap = new HashMap<>();
sampleMap.put("key2", "test value two");
sampleMap.put("key5", "test value five");
sampleMap.put("key4", "test value four");
sampleMap.put("key3", "test value three");
sampleMap.put("key1", "test value one");
System.out.println("Input Map: ");
for (Map.Entry entry: sampleMap.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
// sort map by key
Map<String, String> sortedMap = MapUtils.sortMapByKey(sampleMap);
System.out.println("\nSorted Map: ");
for (Map.Entry entry: sortedMap.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
Input Map:
Key: key1, Value: test value one
Key: key2, Value: test value two
Key: key5, Value: test value five
Key: key3, Value: test value three
Key: key4, Value: test value four
Sorted Map:
Key: key1, Value: test value one
Key: key2, Value: test value two
Key: key3, Value: test value three
Key: key4, Value: test value four
Key: key5, Value: test value five
Happy Coding 😊