1. Introduction
In Java, the ArrayList and HashMap classes are part of the java.util package and are widely used for storing data. ArrayList is an implementation of List interface and can contain duplicate elements. On the other hand, HashMap implements the Map interface and stores key-value pairs. There could be scenarios where you have data in an ArrayList and you want to convert it into a HashMap for faster lookups. In this post, we will demonstrate how to achieve this conversion.
2. Program Steps
1. Create and initialize two ArrayLists: one for keys and one for values.
2. Create a HashMap.
3. Iterate through the ArrayLists and put the elements into the HashMap as key-value pairs.
4. Print the resulting HashMap.
3. Code Program
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ArrayListToHashMap {
public static void main(String[] args) {
// Step 1: Create and initialize two ArrayLists: one for keys and one for values
List<String> keys = new ArrayList<>();
keys.add("Apple");
keys.add("Banana");
keys.add("Cherry");
List<Integer> values = new ArrayList<>();
values.add(10);
values.add(20);
values.add(30);
// Step 2: Create a HashMap
Map<String, Integer> map = new HashMap<>();
// Step 3: Iterate through the ArrayLists and put the elements into the HashMap as key-value pairs
for (int i = 0; i < keys.size(); i++) {
map.put(keys.get(i), values.get(i));
}
// Step 4: Print the resulting HashMap
System.out.println("HashMap: " + map);
}
}
Output:
HashMap: {Apple=10, Banana=20, Cherry=30}
4. Step By Step Explanation
Step 1: Two ArrayLists named keys and values are created and initialized. The keys ArrayList stores Strings, representing the keys of the future HashMap. The values ArrayList stores Integers, representing the values.
Step 2: A HashMap named map is created to store the key-value pairs from the ArrayLists.
Step 3: A for loop is used to iterate through the ArrayLists. For each iteration, the put() method is used to add a key-value pair to the HashMap map, using the elements at the corresponding index in the keys and values ArrayLists.
Step 4: The contents of the resulting HashMap are printed to the console.