1. Introduction
In Java, HashMap is a part of the java.util package, and it implements the Map interface, storing elements in key/value pairs. However, sometimes you might need to convert a HashMap into an ArrayList. In this tutorial, we will discuss a straightforward approach to convert a HashMap into an ArrayList.
2. Program Steps
1. Create and initialize a HashMap.
2. Convert the keys of the HashMap into an ArrayList.
3. Convert the values of the HashMap into another ArrayList.
4. Print the two ArrayLists.
3. Code Program
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HashMapToArrayList {
public static void main(String[] args) {
// Step 1: Create and initialize a HashMap
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 10);
map.put("Banana", 20);
map.put("Cherry", 30);
// Step 2: Convert the keys of the HashMap into an ArrayList
List<String> keyList = new ArrayList<>(map.keySet());
// Step 3: Convert the values of the HashMap into another ArrayList
List<Integer> valueList = new ArrayList<>(map.values());
// Step 4: Print the two ArrayLists
System.out.println("Key List: " + keyList);
System.out.println("Value List: " + valueList);
}
}
Output:
Key List: [Apple, Banana, Cherry] Value List: [10, 20, 30]
4. Step By Step Explanation
Step 1: A HashMap named map is created and initialized with three entries, each consisting of a String key and an Integer value.
Step 2: The keySet() method is used to get the keys from the HashMap, and a new ArrayList named keyList is created from this set.
Step 3: The values() method is used to get the values from the HashMap, and another ArrayList named valueList is created from this collection.
Step 4: Finally, both the keyList and the valueList are printed to the console, showcasing the conversion of the HashMap keys and values into ArrayLists.