How to Sort a Map by key in Java?

Here we will see how to sort a Map by key in java. There are two ways to sort a Map by Key –

 

First Approach

[java]
/**
* Created on Nov 19, 2016 Copyright(c) https://kodehelp.com All Rights Reserved.
*/
package com.kodehelp.util;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
* @author https://kodehelp.com
*
*/
public class SortMapByKey {

/**
* @param args
*/
public static void main(String[] args) {

Map<String, String> unSortedMap = new HashMap<String, String>();

unSortedMap.put("Z", "Zack");
unSortedMap.put("D", "David");
unSortedMap.put("E", "Emily");
unSortedMap.put("B", "Bob");
unSortedMap.put("C", "Catherine");
unSortedMap.put("A", "Alex");
unSortedMap.put("N", "Nancy");
unSortedMap.put("J", "Joe");

System.out.println("=================Unsorted Map ================== ");
printMap(unSortedMap);

System.out.println("=================Sorted Map ================== ");
Map<String, String> treeMap = new TreeMap<String, String>(unSortedMap);
printMap(treeMap);

}

public static <K, V> void printMap(Map<K, V> map) {
for (Map.Entry<K, V> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey()
+ " Value : " + entry.getValue());
}
}

}
[/java]

Second Approach

[java]
/**
* Created on Nov 19, 2016 Copyright(c) https://kodehelp.com All Rights Reserved.
*/
package com.kodehelp.util;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
* @author https://kodehelp.com
*
*/
public class SortMapByKeyExample {

/**
* @param args
*/
public static void main(String[] args) {

Map<String, String> unSortedMap = new HashMap<String, String>();

unSortedMap.put("Z", "Zack");
unSortedMap.put("D", "David");
unSortedMap.put("E", "Emily");
unSortedMap.put("B", "Bob");
unSortedMap.put("C", "Catherine");
unSortedMap.put("A", "Alex");
unSortedMap.put("N", "Nancy");
unSortedMap.put("J", "Joe");

System.out.println("=================Unsorted Map ================== ");
printMap(unSortedMap);

System.out.println("=================Sorted Map ================== ");
Map<String, String> treeMap = new TreeMap<String, String>(new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.compareTo(s2);
}
});
treeMap.putAll(unSortedMap);
printMap(treeMap);

}

public static <K, V> void printMap(Map<K, V> map) {
for (Map.Entry<K, V> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}

}
[/java]

Please Post Your Comments & Reviews

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