Converting Maps to Lists in Java: A Step-by-Step Guide

Understanding the Basics

A map, also known as a hashmap, is a collection of key-value pairs where each key is unique. In our example, we have a map named map that contains integer keys and string values.

The Conversion Process

To convert a map to a list, we can utilize the keySet() and values() methods. These methods allow us to extract the keys and values from the map and store them in separate lists.

Extracting Keys and Values

First, we use the keySet() method to retrieve all the keys from the map. We then create an ArrayList called keyList to store these keys. Similarly, we use the values() method to get all the values and create an ArrayList called valueList to store them.


// Create a map of Integer and String
Map<Integer, String> map = new HashMap<>();

// Extract keys and values from the map
List<Integer> keyList = new ArrayList<>(map.keySet());
List<String> valueList = new ArrayList<>(map.values());

With these simple steps, you’ve successfully converted a map to a list in Java.

Leave a Reply