- 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
Sort HashMap based on keys in Java
Firstly, create a HashMap −
HashMap hm = new HashMap();
Add some elements to the HashMap −
hm.put("Shirts", new Integer(700)); hm.put("Trousers", new Integer(600)); hm.put("Jeans", new Integer(1200)); hm.put("Android TV", new Integer(450)); hm.put("Air Purifiers", new Integer(300)); hm.put("Food Processors", new Integer(950));
Now, sort the HashMap based on keys using TreeMap −
Map<String, String> sort = new TreeMap<String, String>(hm); System.out.println("Sorted Map based on key = "+sort);
The following is an example to sort HasMap based on keys −
Example
import java.util.*; public class Demo { public static void main(String args[]) { HashMap hm = new HashMap(); hm.put("Shirts", new Integer(700)); hm.put("Trousers", new Integer(600)); hm.put("Jeans", new Integer(1200)); hm.put("Android TV", new Integer(450)); hm.put("Air Purifiers", new Integer(300)); hm.put("Food Processors", new Integer(950)); System.out.println("Map = "+hm); Map<String, String> sort = new TreeMap<String, String>(hm); System.out.println("Sorted Map based on key = "+sort); } }
Output
Map = {Shirts=700, Food Processors=950, Air Purifiers=300, Jeans=1200, Android TV=450, Trousers=600} Sorted Map based on key = {Air Purifiers=300, Android TV=450, Food Processors=950, Jeans=1200, Shirts=700, Trousers=600}
- Related Articles
- Sort object array based on another array of keys - JavaScript
- Sorting a HashMap according to keys in Java
- Retrieve all the keys from HashMap in Java
- Sort LinkedHashMap by Keys in Java
- Normal Forms Based on Primary Keys
- Java Program to retrieve the set of all keys in HashMap
- Java Program to Sort map by keys
- Sort LinkedHashMap by Keys using Comparable Interface in Java
- Java Program to retrieve the set of all keys and values in HashMap
- Sorting a HashMap according to keys in C#
- Sort array based on another array in JavaScript
- Java Program to find keys from a Linked HashMap and store it in a list
- Sort search results based on substring position in MySQL
- HashMap in Java
- C program to sort triangles based on area

Advertisements