Java Program to Convert Map (HashMap) to List
Example 1: Convert Map to List
import java.util.*;
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 = new ArrayList(map.keySet());
List<String> valueList = new ArrayList(map.values());
System.out.println("Key List: " + keyList);
System.out.println("Value List: " + valueList);
}
}
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
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);
}
}
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 Collectors
‘ toList()
as a parameter.