How do I convert Map to Array in Java

Published May 16, 2022

Rather than declaring separate variables for each item, you can store multiple values in an array by converting a map to an array. A Map consists of a key and a value pair. Among the list objects, it can contain key values while the other can contain map values separately.

How to convert a Map to Array in Java

Here are the simple steps you need to follow to convert a map to a list:

  • Step 1: First, create the Map object.

  • Step 2: Input elements into it as key-value pairs by calling the put() method

  • Step 3: For the keys of the map, create an ArrayList of integer type. Call keySet() of the Map class in its constructor.

  • Step 4: Assign the values of the map to an ArrayList of String type. Call the values() method of the Map class in its constructor.

  • Step 5: Lastly, print the results of both lists.

 

Example

In this example we are going to follow the above steps to convert Map to an Array

import java.util.ArrayList;

import java.util.HashMap;

import java.util.Map;

public class Convert_Map_to_Array {

            public static void main(String[] args) {

                        Map<Integer, String> ManMap = new HashMap<>();

                        ManMap.put(20, "Python");

                        ManMap.put(30, "Java");

                        ManMap.put(50, "Ruby");

                        ManMap.put(60, "Python");

                  ArrayList<Integer> keyList = new ArrayList<Integer>(ManMap.keySet());

                  ArrayList<String> valueList = new ArrayList<String>(ManMap.values());

                  System.out.println("Map content ::"+keyList);

                  System.out.println("Arraylist ::"+valueList);

              }

}

 

Output:

Map content ::[50, 20, 60, 30]

Arraylist ::[Ruby, Python, Python, Java]

 

Keywords: How to convert a Map to Array in Java , Java Collections, Java

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

105 Views