- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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}
- Related Articles
- Sorting a HashMap according to keys in C#
- Sorting a HashMap according to values in Java
- Sort HashMap based on keys in Java
- Retrieve all the keys from HashMap in Java
- Java Program to retrieve the set of all keys in HashMap
- Sorting a 2D Array according to values in any given column in Java
- Java Program to find keys from a Linked HashMap and store it in a list
- Java Program to retrieve the set of all keys and values in HashMap
- Sorting according to weights of numbers in JavaScript
- Sorting objects according to days name JavaScript
- Java Program to find keys from both the Linked HashMap and store it in a list alternatively
- Sorting numbers according to the digit root JavaScript
- Sorting array according to increasing frequency of elements in JavaScript
- Sorting according to number of 1s in binary representation using JavaScript
- Create a HashMap in Java

Advertisements