English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
It is well known that Java's HashMap does not maintain insertion order by key nor by any other order when adding entries.
But Java provides another API named TreeMap, which keeps its insertion order sorted according to the natural order of its keys. Therefore, to sort the given hash map by keys, we need to insert the map into the TreeMap, and by default, after insertion, we will traverse the same tree graph for sorting, which is the sorted graph we get.
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 Result
myCSV.csv file created using the following text
{Akshay=5, Bakshi=7, Chang=10, Guang=3, Sandy=1, TomTom=2, Veer=8{}