- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
How to sort Map values by key in Java?
Let’s say the following is our Map with unsorted keys −
HashMap<String, String>map = new HashMap<String, String>(); map.put("1", "A"); map.put("6", "B"); map.put("3", "C"); map.put("7", "D"); map.put("5", "E"); map.put("2", "F"); map.put("4", "G"); map.put("8", "H");
Now, sort the above Map. The result of tMap below would be a sorted map by key −
Map<String, String>tMap = new TreeMap<String, String>(map);
Example
import java.util.HashMap; import java.util.Map; import java.util.TreeMap; public class Demo { public static void main(String[] args) { HashMap<String, String>map = new HashMap<String, String>(); map.put("1", "A"); map.put("6", "B"); map.put("3", "C"); map.put("7", "D"); map.put("5", "E"); map.put("2", "F"); map.put("4", "G"); map.put("8", "H"); Map<String, String>tMap = new TreeMap<String, String>(map); System.out.println("Sorted Map values: "+tMap); } }
Output
{1=A, 2=B, 3=C, 4=D, 5=E, 6=F, 7=G, 8=H}
- Related Articles
- Java Program to Sort a Map By Values
- How can we sort a Map by both key and value using lambda in Java?
- Java Program to Sort map by keys
- Sort Dictionary key and values List in Python
- How to sort a dictionary in Python by values?
- How to Sort object of objects by its key value JavaScript
- Java Program to Map String list to lowercase and sort
- How to delete a key from a map in Golang?
- Sort Python Dictionaries by Key or Value
- JavaScript: How to map array values without using "map" method?
- How to filter String stream and map to lower case in Java? Perform sort as well.
- Python program to sort tuples in increasing order by any key.
- How to sort a boxplot by the median values in Pandas?
- Java Program to read map by Map.Entry
- How to check if a key exists in a map in Golang?

Advertisements