Java Program to Convert Map (HashMap) to List

In this program, you’ll learn different techniques to convert a map to a list in Java.

Example 1: Convert Map to List

  1. import java.util.*;
  2. public class MapList {
  3. public static void main(String[] args) {
  4. Map<Integer, String> map = new HashMap<>();
  5. map.put(1, "a");
  6. map.put(2, "b");
  7. map.put(3, "c");
  8. map.put(4, "d");
  9. map.put(5, "e");
  10. List<Integer> keyList = new ArrayList(map.keySet());
  11. List<String> valueList = new ArrayList(map.values());
  12. System.out.println("Key List: " + keyList);
  13. System.out.println("Value List: " + valueList);
  14. }
  15. }

When you run the program, the output will be:

Key List: [1, 2, 3, 4, 5]
Value List: [a, b, c, d, e]

In the above program, we’ve a map of Integer and String named map. Since map contains a key, value pair, we need two lists to store each of them, namely keyList for keys and valueList for values.

We used map’s keySet() method to get all the keys and created an ArrayList keyList from them. Likewise, we used map’s values() method to get all the values and created an ArrayList valueList from them.


Example 2: Convert Map to List using stream

  1. import java.util.*;
  2. import java.util.stream.Collectors;
  3. public class MapList {
  4. public static void main(String[] args) {
  5. Map<Integer, String> map = new HashMap<>();
  6. map.put(1, "a");
  7. map.put(2, "b");
  8. map.put(3, "c");
  9. map.put(4, "d");
  10. map.put(5, "e");
  11. List<Integer> keyList = map.keySet().stream().collect(Collectors.toList());
  12. List<String> valueList = map.values().stream().collect(Collectors.toList());
  13. System.out.println("Key List: " + keyList);
  14. System.out.println("Value List: " + valueList);
  15. }
  16. }

The output of the program is same as Example 1.

In the above program, instead of using ArrayList constructor, we’ve used stream() to convert the map to a list.

We’ve converted the keys and values to stream and convert it to a list using collect() method passing CollectorstoList() as a parameter.