Convert Map keys to List

Given a Map composed of String keys, the following code bit transforms it into a List.

Map<String, String> map = new HashMap<>();
map.put("Key1", "Value1");
// ...
List<String> list = new ArrayList<String>(map.keys());

Convert Map values to List

Given a Map composed of String values, the following code bit transforms it into a List.

Map<String, String> map = new HashMap<>();
map.put("Key1", "Value1");
// ...
List<String> list = new ArrayList<String>(map.values());

Explanation

A very common task in programming is to convert data between different data structures.

The java.util.Map interface represents a data structure capable of holding multiple keys associated to values. A practical use case would be to store a country code into the key, for example, IRL, and the respective value as the country name, such as Ireland.

Map<String, String> map = new HashMap<>();
map.put("IRL", "Ireland");
// ...

In order to retrieve data from a map, you need to know its key. An interesting analogy would be to consider maps as dictionaries, where the word (index) is the key, and the value would be the definition. The following is an example of retrieving data from a map:

// ...
String countryName = map.get("IRL");
// ...

On the other hand, the java.util.List interface represents an enhanced array structure (with dynamic redimensioning and some other nice features), capable of storing multiple items in the same variable. Differently from maps, lists cannot hold two elements per entry (such as the key and the value). It will hold just a value element, as seen in the following example:

List<String> list = new ArrayList<>();
list.add("Ireland");
// ...

An internal index is used to retrieve the data from a list structure in Java. This index starts in 0 and can go up indefinitely (the sky is the limit… I mean, the memory). The following example shows how to retrieve the previously added element from the list:

// ...
String countryName = list.get(0);
// ...

That was a quick overview of maps and lists used in the code bits above. Check other entries for more information!