
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert HashMap to TreeMap in Java
In this article, we will convert a HashMap to a TreeMap in Java. A HashMap is used for storing data as key-value pairs, but it doesn't keep the keys in any particular order. A TreeMap sorts the keys in ascending order. By converting a HashMap to a TreeMap, we can ensure that the keys are stored in a sorted way.
Problem Statement
Given a HashMap filled with key-value pairs, we need to convert it into a TreeMap so that the entries are sorted by the keys.Input
("1", "A"), ("2", "B"), ("3", "C"), ("4", "D"), ("5", "E"),
("6", "F"), ("7", "G"), ("8", "H"), ("9", "I")
Output
Sorted Map = {1=A, 2=B, 3=C, 4=D, 5=E, 6=F, 7=G, 8=H, 9=I}
Steps to convert HashMap to TreeMap
The following are the steps to convert HashMap to TreeMap ?- Import the HashMap, TreeMap, and Map classes from the java.util package.
- Create a HashMap and fill it with some key-value pairs.
- Use the constructor of TreeMap, passing the HashMap as an argument, to automatically sort the keys.
- Return the TreeMap to see the keys sorted in ascending order.
Java program to convert HashMap to TreeMap
The following is an example of converting HashMap to TreeMap ?
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}
Code Explanation
Create a HashMap and add some key-value pairs. After that, we use the TreeMap constructor to automatically sort the entries based on the keys. The result is a TreeMap, where the keys are sorted in ascending order, and we return the final output.
Advertisements