Introduction

Hello, and welcome back! Are you ready for a new challenge? In this unit, we're stepping up a notch to tackle a complex yet intriguing task. It involves parsing complex strings into Java HashMaps and then updating them, which is a common requirement in many real-world tasks. So yes, this unit's session is going to be pretty pragmatic — just the way you like it!

Task Statement

This task involves transforming a given string into a nested HashMap and updating a specific key-value pair within that map. The input string will take the form "Key1=Value1,Key2=Value2,...". When a part of the value is another key-value string, we create a nested HashMap.

For example, the string "A1=B1,C1={D1=E1,F1=G1},I1=J1" should be transformed into the following nested HashMap:

HashMap<String, HashMap<String, String>> dictionary = new HashMap<String, HashMap<String, String>>() {{
    put("A1", new HashMap<String, String>() {{
        put("", "B1");
    }});
    put("C1", new HashMap<String, String>() {{
        put("D1", "E1");
        put("F1", "G1");
    }});
    put("I1", new HashMap<String, String>() {{
        put("", "J1");
    }});
}};

Your Java function should parse this string into the above HashMap, then update the value of the nested key F1 from G1 to some other value, say NewValue. The function should ultimately return the updated HashMap.

Step 1 - Setting Up the Function and Variables

First, set up the function and necessary variables:

import java.util.HashMap;

public class Solution {
    
    public static HashMap<String, HashMap<String, String>> parseString(String inputString) {
        HashMap<String, HashMap<String, String>> result = new HashMap<>();

        String key = ""; // to store the outer map key
        HashMap<String, String> innerMap = new HashMap<>(); // to store the inner map
        boolean inInnerMap = false; // flag to check if we are inside an inner map
        int i = 0; // to iterate through the string
Step 2 - Handling the Opening and Closing Braces

Next, handle the opening and closing braces. If an inner map is encountered, set the flag and prepare to parse it:

        while (i < inputString.length()) {
            if (inputString.charAt(i) == '{') {
                // Entering an inner map
                inInnerMap = true;
                i++; // Skip the '{'
            } else if (inputString.charAt(i) == '}') {
                // Exiting an inner map
                result.put(key, innerMap);
                innerMap = new HashMap<>();
                inInnerMap = false;
                i++; // Skip the '}'
                if (i < inputString.length() && inputString.charAt(i) == ',') {
                    i++; // Skip the ',' after '}'
                }
            }
Step 3 - Parsing Outer Map Key-Value Pairs

Handle parsing key-value pairs in the outer map:

            else if (!inInnerMap) {
                // Parsing key-value pairs in the outer map
                int equalPos = inputString.indexOf('=', i);
                int commaPos = inputString.indexOf(',', equalPos);
                if (commaPos == -1) commaPos = inputString.length();

                key = inputString.substring(i, equalPos);
                String value = inputString.substring(equalPos + 1, commaPos);

                if (value.contains("{")) {
                    // Value is a nested map, will be processed separately
                    i = equalPos + 1; // Move forward to process the nested part
                } else {
                    // Value is a simple string, add to result map
                    result.put(key, new HashMap<String, String>() {{
                        put("", value);
                    }});
                    i = commaPos + 1; // Move past the comma
                }
            }
Step 4 - Parsing Inner Map Key-Value Pairs

Handle parsing key-value pairs inside the inner map:

            else if (inInnerMap) {
                // Parsing key-value pairs inside the inner map
                int equalPos = inputString.indexOf('=', i);
                int commaPos = inputString.indexOf(',', equalPos);
                int bracePos = inputString.indexOf('}', equalPos);

                // Determine the next delimiter that ends the current key-value pair
                int endPos = Math.min(commaPos < bracePos ? commaPos : inputString.length(), bracePos);
                if (endPos == inputString.length()) endPos = Math.max(commaPos, bracePos);

                String innerKey = inputString.substring(i, equalPos);
                String innerValue = inputString.substring(equalPos + 1, endPos);
                innerMap.put(innerKey, innerValue);

                i = endPos;
                if (i < inputString.length() && inputString.charAt(i) == ',') {
                    i++; // Skip the comma
                }
            }
        }

        return result;
    }
Step 5 - Updating the Value in the Map

Now that we have the parsed HashMap, we can move into the final phase of the task: updating a specific key-value pair. Here’s the function to update a value in the nested HashMap:

    public static void updateMap(HashMap<String, HashMap<String, String>> map, String key, String value) {
        for (HashMap<String, String> innerMap : map.values()) {
            if (innerMap.containsKey(key)) {
                // Key found, update the value
                innerMap.put(key, value);
                return;
            }
        }
    }
Step 6 - Putting It All Together

Finally, we put everything together in one function to parse the string and update the value:

import java.util.HashMap;

public class Solution {
    
    public static HashMap<String, HashMap<String, String>> parseString(String inputString) {
        HashMap<String, HashMap<String, String>> result = new HashMap<>();

        String key = ""; // to store the outer map key
        HashMap<String, String> innerMap = new HashMap<>(); // to store the inner map
        boolean inInnerMap = false; // flag to check if we are inside an inner map
        int i = 0; // to iterate through the string
        while (i < inputString.length()) {
            if (inputString.charAt(i) == '{') {
                // Entering an inner map
                inInnerMap = true;
                i++; // Skip the '{'
            } else if (inputString.charAt(i) == '}') {
                // Exiting an inner map
                result.put(key, innerMap);
                innerMap = new HashMap<>();
                inInnerMap = false;
                i++; // Skip the '}'
                if (i < inputString.length() && inputString.charAt(i) == ',') {
                    i++; // Skip the ',' after '}'
                }
            }
            else if (!inInnerMap) {
                // Parsing key-value pairs in the outer map
                int equalPos = inputString.indexOf('=', i);
                int commaPos = inputString.indexOf(',', equalPos);
                if (commaPos == -1) commaPos = inputString.length();

                key = inputString.substring(i, equalPos);
                String value = inputString.substring(equalPos + 1, commaPos);

                if (value.contains("{")) {
                    // Value is a nested map, will be processed separately
                    i = equalPos + 1; // Move forward to process the nested part
                } else {
                    // Value is a simple string, add to result map
                    result.put(key, new HashMap<String, String>() {{
                        put("", value);
                    }});
                    i = commaPos + 1; // Move past the comma
                }
            }
            else if (inInnerMap) {
                // Parsing key-value pairs inside the inner map
                int equalPos = inputString.indexOf('=', i);
                int commaPos = inputString.indexOf(',', equalPos);
                int bracePos = inputString.indexOf('}', equalPos);

                // Determine the next delimiter that ends the current key-value pair
                int endPos = Math.min(commaPos < bracePos ? commaPos : inputString.length(), bracePos);
                if (endPos == inputString.length()) endPos = Math.max(commaPos, bracePos);

                String innerKey = inputString.substring(i, equalPos);
                String innerValue = inputString.substring(equalPos + 1, endPos);
                innerMap.put(innerKey, innerValue);

                i = endPos;
                if (i < inputString.length() && inputString.charAt(i) == ',') {
                    i++; // Skip the comma
                }
            }
        }

        return result;
    }
    public static void updateMap(HashMap<String, HashMap<String, String>> map, String key, String value) {
        for (HashMap<String, String> innerMap : map.values()) {
            if (innerMap.containsKey(key)) {
                // Key found, update the value
                innerMap.put(key, value);
                return;
            }
        }
    }
    public static HashMap<String, HashMap<String, String>> parseStringAndUpdateValue(String inputString, String updateKey, String newValue) {
        // Parse the input string into a nested HashMap
        HashMap<String, HashMap<String, String>> map = parseString(inputString);
        // Update the specific key-value pair
        updateMap(map, updateKey, newValue);
        return map;
    }

    public static void main(String[] args) {
        String input = "A1=B1,C1={D1=E1,F1=G1},I1=J1";
        String updateKey = "F1";
        String newValue = "NewValue";

        HashMap<String, HashMap<String, String>> updatedMap = parseStringAndUpdateValue(input, updateKey, newValue);
        System.out.println(updatedMap);
    }
}
Lesson Summary

Well done! You've completed an intensive hands-on session dealing with complex strings and nested HashMaps in Java. This type of task often mirrors real-life scenarios where you process complex data and make updates based on particular criteria.

Now it's your turn to reinforce what you've learned in this unit. Try practicing with different strings and attempting to update various key-value pairs. With practice, you'll be able to apply these coding strategies to a wide range of problems. Happy coding!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal