Convert Map (HashMap) to List in Java

Exercise:

Write a Java Program to convert map (HashMap) to list.

1.Convert Map to List

Click Here to View the Solution!
import java.util.*;
public class MapToList {
  
     public static void main(String[] args) {
         Map<Integer, String> map = new HashMap<>();
         map.put(1, "a");
         map.put(2, "b");
         map.put(3, "c");
         map.put(4, "d");
         map.put(5, "e");
  
         List<Integer> keyList = new ArrayList(map.keySet());
         List<String> valueList = new ArrayList(map.values());
         System.out.println("Key List: " + keyList);
         System.out.println("Value List: " + valueList);
    }
 } 
Click Here to View the Output!
 Key List: [1, 2, 3, 4, 5]
 Value List: [a, b, c, d, e]
Click Here to View the Explanation!
  • In this program, initially a map has been created with Integer and String types for the key, value pair respectively. As keys and values are in pair form in the map, they will have to be converted into two separate lists for storing them as arraylists. Thus, two lists namely keyList and valueList have been created for this very purpose.
  • For retrieving all the keys in the map, a map’s method called keySet() has been utilized which returns all the keys of the map. These keys are then put as input for the newly created keyList.
  • Similarly, in order to get all the values in the map, a map method called values() has been used. These values are then used to create a list called valueList.

2.Convert Map to List

Click Here to View the Solution!
 import java.util.*;
 import java.util.stream.Collectors;
  
 public class MapList {
     public static void main(String[] args) {
  
         Map<Integer, String> map = new HashMap<>();
         map.put(1, "a");
         map.put(2, "b");
         map.put(3, "c");
         map.put(4, "d");
         map.put(5, "e");
  
   List<Integer> keyList = map.keySet().stream().collect(Collectors.toList());
   List<String> valueList = map.values().stream().collect(Collectors.toList());
  
         System.out.println("Key List: " + keyList);
         System.out.println("Value List: " + valueList);
     }
 } 
Click Here to View the Output!
 Key List: [1, 2, 3, 4, 5]
 Value List: [a, b, c, d, e]
Click Here to View the Explanation!
  • In this program, conversion from map to list takes place through streams thus the usual arraylist constructor is not used.
  • After getting the key and value sets from map methods, these values are converted into streams and then further converted to lists through .collect() method which has Collectors’ toList() passed as an argument to it.