- 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
Java Program to convert HashMap to TreeMap
To convert HashMap to TreeMap, let us first create a Map with key-value pair −
Map<String, String>map = new HashMap<String, String>(); map.put("1", "A"); map.put("2", "B"); map.put("3", "C"); map.put("4", "D"); map.put("5", "E"); map.put("6", "F"); map.put("7", "G");
Now, convert the above HashMap to TreeMap −
Map<String, String>sorted = 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[] a) { Map<String, String>map = new HashMap<String, String>(); map.put("1", "A"); map.put("2", "B"); map.put("3", "C"); map.put("4", "D"); map.put("5", "E"); map.put("6", "F"); map.put("7", "G"); map.put("8", "H"); map.put("9", "I"); Map<String, String>sorted = new TreeMap<String, String>(map); System.out.println("Sorted Map = "+sorted); } }
Output
Sorted Map = {1=A, 2=B, 3=C, 4=D, 5=E, 6=F, 7=G, 8=H, 9=I}
- Related Articles
- Program to convert HashMap to TreeMap in Java
- Difference Between HashMap and TreeMap in Java
- Difference between TreeMap, HashMap, and LinkedHashMap in Java
- Differences between TreeMap, HashMap and LinkedHashMap in Java
- How to implement HashMap, LinkedHashMap, and TreeMap in JShell in Java 9?
- Difference between TreeMap, HashMap and LinkedHashMap in Java programming
- What is the differences between TreeMap, HashMap and LinkedHashMap in Java?
- Java Program to get Tail Map from TreeMap
- Java Program to get Sub Map from TreeMap
- Java Program to Iterate over a HashMap
- Java Program to get highest key stored in TreeMap
- Java Program to Iterate through Elements of HashMap
- Java Program to remove a key from a HashMap
- Java Program to remove key value pair from HashMap?
- Java Program to initialize a HashMap with Lambda Expressions

Advertisements