Conversion of Java Maps to List
Converting Java Maps to Lists is a common operation in Java programming, especially when you need to work with the data stored in a Map in a different format or order. The conversion allows developers to manipulate and process the data in a more convenient way as Lists provide indexed access to elements while Maps store data as key-value pairs.
Example 1:
Input:
Student 1: - Roll No: 101 - Name: Alice Student 2: - Roll No: 102 - Name: Bob Student 3: - Roll No: 103 - Name: Charlie
Output:
List of Roll Numbers of Students [101, 102, 103] List of Names of Students [Alice, Bob, Charlie]
Example 2:
Input:
Product 1: - ID: 001 - Name: Laptop Product 2: - ID: 002 - Name: Smartphone Product 3: - ID: 003 - Name: Headphones Product 4: - ID: 004 - Name: T-shirts Product 5: - ID: 005 - Name: Jeans
Output:
List of Product IDs [001, 002, 003, 004, 005] List of Product Names [Laptop, Smartphone, Headphones, T-shirts, Jeans]
Approach 1: Using Iteration
ALGORITHM:
Step 1: Initialize a Scanner to read user input.
Step 2: Create a HashMap (studentMap) to store student information with Roll No as keys and Names as values.
Step 3: Display a message for "Example 1: Converting Student Information."
Step 4: For each student (loop 3 times):
Step 4.1: Display "Student [i]:" where [i] is the student number (1 to 3).
Step 4.2: Prompt the user for Roll No and read it as an integer.
Step 4.3: Consume the newline character.
Step 4.4: Prompt the user for the Name and read it as a string.
Step 4.5: Put the Roll No and Name into studentMap.
Step 5: Create two ArrayLists (rollNumbers and studentNames) to store student Roll Numbers and Names.
Step 6: For each entry in studentMap:
Step 6.1: Extract the Roll No and Name.
Step 6.2: Add the Roll No to rollNumbers.
Step 6.3: Add the Name to studentNames.
Step 7: Display "List of Roll Numbers of Students."
Step 8: Print rollNumbers.
Step 9: Display "List of Names of Students."
Step 10: Print studentNames.
Step 11: Clear studentMap to prepare for the next example.
Step 12: Display "Example 2: Converting Product Information."
Step 13: Create a HashMap (productMap) to store product information with Product ID as keys and Names as values.
Step 14: For each product (loop 5 times):
Step 14.1: Display "Product [i]:" where [i] is the product number (1 to 5).
Step 14.2: Prompt the user for the Product ID and read it as a string.
Step 14.3: Prompt the user for the Product Name and read it as a string.
Step 14.4: Put the Product ID and Name into productMap.
Step 15: Create two ArrayLists (productIDs and productNames) to store product IDs and Names.
Step 16: For each entry in productMap:
Step 16.1: Extract the Product ID and Name.
Step 16.2: Add the Product ID to productIDs.
Step 16.3: Add the Product Name to productNames.
Step 17: Display "List of Product IDs."
Step 18: Print productIDs.
Step 19: Display "List of Product Names."
Step 20: Print productNames.
Step 21: Close the Scanner to release resources.
Step 22: End the program.
Implementation:
The implementation of the above steps given below
FileName: MapToListConversion.java
import java.util.*; public class MapToListConversion { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Example 1: Converting Student Information System.out.println("Example 1: Converting Student Information"); MapstudentMap = new HashMap<>(); // Collect student information from the user for (int i = 1; i <= 3; i++) { System.out.println("Student " + i + ":"); System.out.print("- Enter Roll No: "); int rollNo = scanner.nextInt(); scanner.nextLine(); // Consume the newline character System.out.print("- Enter Name: "); String studentName = scanner.nextLine(); studentMap.put(rollNo, studentName); } // Convert the Map into Lists List rollNumbers = new ArrayList<>(); List studentNames = new ArrayList<>(); for (Map.Entry entry : studentMap.entrySet()) { int rollNo = entry.getKey(); String name = entry.getValue(); rollNumbers.add(rollNo); studentNames.add(name); } // Display the Lists of Student Roll Numbers and Names System.out.println(" List of Roll Numbers of Students"); System.out.println(rollNumbers); System.out.println(" List of Names of Students"); System.out.println(studentNames); // Clear the map for the next example studentMap.clear(); // Example 2: Converting Product Information System.out.println(" Example 2: Converting Product Information"); Map productMap = new HashMap<>(); // Collect product information from the user for (int i = 1; i <= 5; i++) { System.out.println("Product " + i + ":"); System.out.print("- Enter ID: "); String productID = scanner.nextLine(); System.out.print("- Enter Name: "); String productName = scanner.nextLine(); productMap.put(productID, productName); } // Convert the Map into Lists List productIDs = new ArrayList<>(); List productNames = new ArrayList<>(); for (Map.Entry entry : productMap.entrySet()) { String id = entry.getKey(); String name = entry.getValue(); productIDs.add(id); productNames.add(name); } // Display the Lists of Product IDs and Names System.out.println(" List of Product IDs"); System.out.println(productIDs); System.out.println(" List of Product Names"); System.out.println(productNames); scanner.close(); } }
Output:
Example 1: Converting Student Information Student 1: - Enter Roll No: 101 - Enter Name: Alice Student 2:- Enter Roll No: 102 - Enter Name: Bob Student 3: - Enter Roll No: 103 - Enter Name: Charlie List of Roll Numbers of Students [101, 102, 103] List of Names of Students [Alice, Bob, Charlie] Example 2: Converting Product Information Product 1:- Enter ID: 001 - Enter Name: Smartphone Product 2: - Enter ID: 002 - Enter Name: Laptop Product 3: - Enter ID: 003 - Enter Name: Headphones Product 4: - Enter ID: 004 - Enter Name: T-shirts Product 5: - Enter ID: 005 - Enter Name: Jeans List of Product IDs [001, 002,003, 004, 005] List of Product Names [Smartphone, Laptop, T-shirts, Jeans, Headphones]
Complexity Analysis:
Time Complexity:
The time complexity is dominated by the linear time operations, and it can be expressed as O(n + 2m), where n is the number of students or products entered, and m is the number of entries in the Map.
Space Complexity:
The space complexity is primarily determined by the space used to store the Maps and Lists and it can be expressed as O(m) where m is the number of entries in the Map.
Approach 2: Using Recursion
ALGORITHM:
Step 1: Initialize a Scanner to read user input.
Step 2: Create a HashMap (studentMap) to store student information with Roll No as keys and Names as values.
Step 3: Display a message for "Example 1: Converting Student Information."
Step 4: Call the collectStudentInfo recursive method to collect student information.
Step 5: Create two ArrayLists (rollNumbers and studentNames) to store student Roll Numbers and Names.
Step 6: Call the convertMapToLists recursive method to convert studentMap into Lists.
Step 7: Display "List of Roll Numbers of Students."
Step 8: Print rollNumbers.
Step 9: Display "List of Names of Students."
Step 10: Print studentNames.
Step 11: Clear studentMap to prepare for the next example.
Step 12: Display "Example 2: Converting Product Information."
Step 13: Create a HashMap (productMap) to store product information with Product ID as keys and Names as values.
Step 14: Call the collectProductInfo recursive method to collect product information.
Step 15: Create two ArrayLists (productIDs and productNames) to store product IDs and Names.
Step 16: Call the convertMapToLists recursive method to convert productMap into Lists.
Step 17: Display "List of Product IDs."
Step 18: Print productIDs.
Step 19: Display "List of Product Names."
Step 20: Print productNames.
Step 21: Close the Scanner to release resources.
Step 22: End the program.
Step 23: Recursive Method collectStudentInfo:
Step 23.1: If studentNumber is less than or equal to 3:
Step 23.2: Display "Student [i]:" where [i] is the student number (1 to 3).
Step 23.3: Prompt the user for Roll No and read it as an integer.
Step 23.4: Consume the newline character.
Step 23.5: Prompt the user for the Name and read it as a string.
Step 23.6: Put the Roll No and Name into studentMap.
Step 23.7: Recursive call with studentNumber + 1 to collect the next student.
Step 24: Recursive Method collectProductInfo:
Step 24.1: If productNumber is less than or equal to 5:
Step 24.2: Display "Product [i]:" where [i] is the product number (1 to 5).
Step 24.3: Prompt the user for the Product ID and read it as a string.
Step 24.4: Prompt the user for the Product Name and read it as a string.
Step 24.5: Put the Product ID and Name into productMap.
Step 24.6: Recursive call with productNumber + 1 to collect the next product.
Step 25: Recursive Method convertMapToLists:
Step 25.1: Iterate through the entries in the map.
Step 25.2: For each entry, add the key to keysList and the value to valuesList
Implementation:
The implementation of the above steps given below
FileName: MapToListConversion.java
import java.util.*; public class MapToListConversion { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Example 1: Converting Student Information System.out.println("Example 1: Converting Student Information"); MapstudentMap = new HashMap<>(); // Collect student information recursively collectStudentInfo(studentMap, scanner, 1); // Convert the Map into Lists List rollNumbers = new ArrayList<>(); List studentNames = new ArrayList<>(); convertMapToLists(studentMap, rollNumbers, studentNames); // Display the Lists of Student Roll Numbers and Names System.out.println(" List of Roll Numbers of Students"); System.out.println(rollNumbers); System.out.println(" List of Names of Students"); System.out.println(studentNames); // Clear the map for the next example studentMap.clear(); // Example 2: Converting Product Information System.out.println(" Example 2: Converting Product Information"); Map productMap = new HashMap<>(); // Collect product information recursively collectProductInfo(productMap, scanner, 1); // Convert the Map into Lists List productIDs = new ArrayList<>(); List productNames = new ArrayList<>(); convertMapToLists(productMap, productIDs, productNames); // Display the Lists of Product IDs and Names System.out.println(" List of Product IDs"); System.out.println(productIDs); System.out.println(" List of Product Names"); System.out.println(productNames); scanner.close(); } // Recursive method to collect student information private static void collectStudentInfo(Map studentMap, Scanner scanner, int studentNumber) { if (studentNumber <= 3) { System.out.println("Student " + studentNumber + ":"); System.out.print("- Enter Roll No: "); int rollNo = scanner.nextInt(); scanner.nextLine(); // Consume the newline character System.out.print("- Enter Name: "); String studentName = scanner.nextLine(); studentMap.put(rollNo, studentName); // Recursive call for the next student collectStudentInfo(studentMap, scanner, studentNumber + 1); } } // Recursive method to collect product information private static void collectProductInfo(Map productMap, Scanner scanner, int productNumber) { if (productNumber <= 5) { System.out.println("Product " + productNumber + ":"); System.out.print("- Enter ID: "); String productID = scanner.nextLine(); System.out.print("- Enter Name: "); String productName = scanner.nextLine(); productMap.put(productID, productName); // Recursive call for the next product collectProductInfo(productMap, scanner, productNumber + 1); } } // Recursive method to convert a Map to Lists private static void convertMapToLists(Map map, List keysList, List valuesList) { for (Map.Entry entry : map.entrySet()) { keysList.add(entry.getKey()); valuesList.add(entry.getValue()); } } }
Output:
Example 1: Converting Student Information Student 1: - Enter Roll No: 101 - Enter Name: Alice Student 2:- Enter Roll No: 102 - Enter Name: Bob Student 3: - Enter Roll No: 103 - Enter Name: Charlie List of Roll Numbers of Students [101, 102, 103] List of Names of Students [Alice, Bob, Charlie] Example 2: Converting Product Information Product 1:- Enter ID: 001 - Enter Name: Smartphone Product 2: - Enter ID: 002 - Enter Name: Laptop Product 3: - Enter ID: 003 - Enter Name: Headphones Product 4: - Enter ID: 004 - Enter Name: T-shirts Product 5: - Enter ID: 005 - Enter Name: Jeans List of Product IDs [001, 002,003, 004, 005] List of Product Names [Smartphone, Laptop, T-shirts, Jeans, Headphones]
Complexity Analysis:
Time Complexity:
The time complexity is dominated by linear time operations, and it can be expressed as O(n + 2m), where n is the number of students or products entered, and m is the number of entries in the map.
Space Complexity:
The space complexity is primarily determined by the space used to store the Maps and Lists, and it can be expressed as O(m), where m is the number of entries in the map.
Applications:
Data Transformation: When dealing with data from external sources like databases or APIs, it's common to receive data as key-value pairs in a Map. Converting this data into Lists makes it easier to process and manipulate for various purposes.
Data Presentation: In user interfaces or reports, you might want to display data in a tabular format. Lists are often more suitable for presenting data in rows or columns, making them easier to render and navigate.
Sorting and Filtering: Lists provide convenient methods for sorting and filtering data. You can convert a Map to a List, apply sorting algorithms or filters, and obtain results in a specific order or meeting specific criteria.
Iterative Processing: Lists support efficient iteration over elements using indices. This is valuable when you need to perform operations on data elements sequentially or in a specific order.
Data Export: When exporting data to various formats like CSV or Excel, Lists are often the preferred data structure. You can easily convert a List to the desired format for export purposes.
Data Serialization: Lists are suitable for serialization purposes, allowing you to save data to a file or send it over a network in a structured format.
Data Validation: Lists can be used for data validation tasks. You can iterate through a List to check for data consistency or validate data against predefined criteria.
Charting and Visualization: Lists are often used to feed data into charting libraries for creating graphs and visual representations of data.
Machine Learning and Analysis: In machine learning and data analysis, data is commonly organized as Lists to train models, perform feature selection, or perform predictive analytics.