How to Convert a Map to List in Java

Suppose we want to convert a Java hashmap into a list.

Let’s assuming this is our map.

Map<Key, Value> map;

Our list will either hold all the keys in that map, or all the values in that map.

Creating a List of Map Keys

To obtain the keys of a map, we can use Map.keySet().

This returns a Set<Key>, but we can easily create a list from a set in Java using the ArrayList constructor.

List<Key> listOfKeys = new ArrayList<Key>(map.keySet());

Creating a List of Map Values

To obtain the values of a map, we can use Map.values().

This returns a Collection<Key>, but we can also create a list from a Collection using the constructor.

List<Value> listOfValues = new ArrayList<Value>(map.values());

Using the Stream API

If we’re using Java 8+, we have access to the Stream API.

List<Key> listOfKeys = map.keySet().stream().collect(Collectors.toList());
List<Value> listOfValues = map.values().stream().collect(Collectors.toList());