- 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
Java program to convert the contents of a Map to list
The Map class's object contains key and value pairs. You can convert it into two list objects one which contains key values and the one which contains map values separately.
To convert a map to list −
- Create a Map object.
- Using the put() method insert elements to it as key, value pairs
- Create an ArrayList of integer type to hold the keys of the map. In its constructor call the method keySet() of the Map class.
- Create an ArrayList of String type to hold the values of the map. In its constructor call the method values() of the Map class.
- Print the contents of both lists.
Example
import java.util.HashMap; import java.uitl.ArrayList; import java.util.Map; public class MapTohashMap { public static void main(String args[]){ Map<Integer, String> myMap = new HashMap<>(); myMap.put(1, "Java"); myMap.put(2, "JavaFX"); myMap.put(3, "CoffeeScript"); myMap.put(4, "TypeScript"); ArrayList<Integer> keyList = new ArrayList<Integer>(myMap.keySet()); ArrayList<String> valueList = new ArrayList<String>(myMap.values()); System.out.println("contents of the list holding keys the map ::"+keyList); System.out.println("contents of the list holding values of the map ::"+valueList); } }
Output
contents of the list holding keys the map::[1, 2, 3, 4] contents of the list holding values of the map::[Java, JavaFX, CoffeeScript, Typescript]
Advertisements