![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
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
Program to convert HashMap to TreeMap in Java
At first create a HashMap −
Map<String, String> map = new HashMap<>(); map.put("1", "One"); map.put("2", "Two"); map.put("3", "Three"); map.put("4", "Four"); map.put("5", "Five"); map.put("6", "Six");
Now, convert the above HashMap to TreeMap −
Map<String, String> treeMap = new TreeMap<>(); treeMap.putAll(map);
Example
Following is the program to convert HashMap to TreeMap in Java −
import java.util.*; import java.util.stream.*; public class Demo { public static void main(String args[]) { Map<String, String> map = new HashMap<>(); map.put("1", "One"); map.put("2", "Two"); map.put("3", "Three"); map.put("4", "Four"); map.put("5", "Five"); map.put("6", "Six"); map.put("7", "Seven"); map.put("8", "Eight"); map.put("9", "Nine"); System.out.println("HashMap = " + map); Map<String, String> treeMap = new TreeMap<>(); treeMap.putAll(map); System.out.println("TreeMap (HashMap to TreeMap) " + treeMap); } }
Output
HashMap = {1=One, 2=Two, 3=Three, 4=Four, 5=Five, 6=Six, 7=Seven, 8=Eight, 9=Nine} TreeMap (HashMap to TreeMap) {1=One, 2=Two, 3=Three, 4=Four, 5=Five, 6=Six, 7=Seven, 8=Eight, 9=Nine}
Advertisements