Sorting a HashMap according to keys in Java


As we know that Hash map in Java does not maintain insertion order either by key or by order.Also it does not maintain any other order while adding entries to it.

But Java provide another API named as TreeMap which maintain its insertion order sorted according to the natural ordering of its keys.So in order to sort our given Hash map according to keys we would insert our map into a tree map which by default insert according to key sorting.After insertion we would transverse same tree map which is sorted and is our resultant sorted map.

Example

 Live Demo

import java.util.HashMap;
import java.util.TreeMap;
public class HashMapSortByKey {
   public static void main(String[] args) {
      HashMap<String,Integer> hMap = new HashMap<>();
      TreeMap<String,Integer> sortedMap = new TreeMap<>();
      hMap.put("Akshay",5);
      hMap.put("Veer",8);
      hMap.put("Guang",3);
      hMap.put("Bakshi",7);
      hMap.put("TomTom",2);
      hMap.put("Chang",10);
      hMap.put("Sandy",1);
      sortedMap = sortByKey(hMap);
      System.out.println(sortedMap);
   }
   public static TreeMap<String,Integer> sortByKey(HashMap<String,Integer> mapToSort) {
      TreeMap<String,Integer> sortedMap = new TreeMap<>();
      sortedMap.putAll(mapToSort);
      return sortedMap;
   }
}

Output

myCSV.csv file created with following text

{Akshay=5, Bakshi=7, Chang=10, Guang=3, Sandy=1, TomTom=2, Veer=8}

Updated on: 25-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements