Java program to convert the contents of a Map to list

Object Oriented ProgrammingJava8Java Programming

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]
raja
Published on 26-Apr-2018 12:08:13
Advertisements