1. Introduction
In Java, a Map can store key-value pairs, where each key maps to a value. The value can be any object, including another collection like a List. Sometimes, we may encounter a situation where we have a Map where the values are List objects, and we need to perform conversions or manipulations on this structure.
2. Program Steps
1. Import necessary libraries.
2. Create a Map object where the values are List objects.
3. Perform any necessary conversion or operation on the Map of List objects.
4. Display the result.
3. Code Program
// Step 1: Import necessary libraries
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MapOfListsExample {
public static void main(String[] args) {
// Step 2: Create a Map object where the values are List objects
Map<String, List<String>> mapOfLists = new HashMap<>();
List<String> list1 = new ArrayList<>();
list1.add("Apple");
list1.add("Banana");
List<String> list2 = new ArrayList<>();
list2.add("Cat");
list2.add("Dog");
mapOfLists.put("Fruits", list1);
mapOfLists.put("Animals", list2);
// Step 3: Perform any necessary conversion or operation on the Map of List objects
// In this example, we simply print out the elements
// Step 4: Display the result
System.out.println("Map of Lists:");
for (Map.Entry<String, List<String>> entry : mapOfLists.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
Output:
Map of Lists: Fruits: [Apple, Banana] Animals: [Cat, Dog]
4. Step By Step Explanation
Step 1: The necessary libraries are imported for handling maps and lists.
Step 2: A Map object named mapOfLists is created where the values are List objects. Two List objects, list1 and list2, are created and populated with strings representing fruits and animals, respectively. These lists are then added to the mapOfLists with corresponding keys.
Step 3: This step is where we would perform any necessary conversion or operation on the Map of List objects. In this example, we simply print out the elements.
Step 4: The contents of the Map of List objects are printed to the console, displaying the categories (Fruits and Animals) and their corresponding elements.