How to Sort a Map by key in Java?

DeeKay November 20, 2016 at 2:00 am · java.util, sorting

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

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

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

/**
 * @author http://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());
        }
    }

}

Second Approach

/**
 * Created on Nov 19, 2016 Copyright(c) http://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 http://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());
		}
	}

}