There is no need to reinvent the wheel. The Google Guava library provides the Splitter class.

Here's how you can use it along with some test code:

package com.sandbox;

import com.google.common.base.Splitter;
import org.junit.Test;

import java.util.Map;

import static org.junit.Assert.assertEquals;

public class SandboxTest {

    @Test
    public void testQuestionInput() {
        Map<String, String> map = splitToMap("A=4 H=X PO=87");
        assertEquals("4", map.get("A"));
        assertEquals("X", map.get("H"));
        assertEquals("87", map.get("PO"));
    }

    private Map<String, String> splitToMap(String in) {
        return Splitter.on(" ").withKeyValueSeparator("=").split(in);
    }

}
Answer from Daniel Kaplan on Stack Overflow
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java string โ€บ converting string or string array to map in java
Converting String or String Array to Map in Java | Baeldung
January 8, 2024 - Finally, the assertEquals() method compares the expectedMap with the resultMap to ensure that the conversion is performed correctly and the output Map matches the expected one. If we have an array of Strings, where each element represents a key-value pair, we can convert it into a Map:
Discussions

collections - How to convert String into Hashmap in java - Stack Overflow
Extract the "key, value" pairs ... the map. ... questions related to logic description are highly discouraged as there can be multiple solutions for the above and its far off topic. by the way what was your approach did you try something or get stuck somewhere then we can help ... This works when I know what key is exactly and how many keys are there,but if I have like 10 keys in String. ... I tried convert the same using ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
lambda - Java 8: How to convert String to Map<String,String>? - Stack Overflow
Split the string by , to get individual map entries. More on stackoverflow.com
๐ŸŒ stackoverflow.com
October 8, 2018
apex - How to convert Map<String,Object> into Map<string,string>()? - Salesforce Stack Exchange
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... strJSON= res.getBody(); system.debug('strJson>>>>>'+strJSON); Map mapJSON = (Map) JSON.deserializeUntyped(strJSON); Map mapLocalSemi = (Map More on salesforce.stackexchange.com
๐ŸŒ salesforce.stackexchange.com
April 1, 2016
How can I convert a string to a map?
Maybe something like thisโ€ฆ variable "count" { type = number default = 0 } locals { settings = var.count == 0 ? {} : { count = var.count } } resource "example" "example" { dynamic "setting" { for_each = local.settings content { count = setting.value["count"] } } } Edit: Formated text for clarity. Edit 2: Rename variable settings -> count More on reddit.com
๐ŸŒ r/Terraform
9
3
January 26, 2023
๐ŸŒ
Java Code Geeks
examples.javacodegeeks.com โ€บ home โ€บ java development โ€บ core java
Converting String or String Array to Map in Java - Java Code Geeks
October 10, 2023 - After running this code, we will have a Map containing the key-value pairs extracted from the input string. We can also use the String.split() method to convert a string to a map in Java.
๐ŸŒ
Mkyong
mkyong.com โ€บ home โ€บ java โ€บ convert json string to map using jackson
Convert JSON string to Map using Jackson | mkyong.com
April 23, 2024 - ObjectMapper mapper = new ... mapper.readValue(json, Map.class); // Convert JSON string to Map Map<String, Object> map = mapper.readValue(json, new TypeReference<>() {}); // Output the contents of the Map to verify the conversion ...
๐ŸŒ
Javatpoint
javatpoint.com โ€บ convert-string-to-map-in-java
Convert String to Map in Java - Javatpoint
Java Program to swap two string variables without using third or temp variable.
๐ŸŒ
KapreSoft
kapresoft.com โ€บ java โ€บ 2023 โ€บ 05 โ€บ 03 โ€บ java-string-to-map.html
Java โ€ข Converting Strings To Map | KapreSoft
May 3, 2023 - To perform this conversion, we can split the input string into an array of key-value pairs using the delimiter, then split each key-value pair into an array of key and value using another delimiter, such as the equals sign.
Find elsewhere
๐ŸŒ
Reddit
reddit.com โ€บ r/terraform โ€บ how can i convert a string to a map?
r/Terraform on Reddit: How can I convert a string to a map?
January 26, 2023 -

My use case is I have an optional block in a resource that I'm trying to templatize.

That block has only one parameter: a number. instead of a user creating a map variable in the root, I want him to be able to just put in a number.

But dynamic blocks only take maps as an input. Any idea what I can do?

To add, that block parameter is named 'count'. Which Terraform is throwing a fit over...what can I do!?

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ convert-string-or-string-array-to-hashmap-in-java
Convert String or String Array to HashMap In Java - GeeksforGeeks
July 23, 2025 - First, we split the String by a comma and store it in an array parts. After the split we have the following content: ... And then iterate on parts and split the student data to get the student name and roll number.
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ convert-json-string-to-java-map-with-jackson
Convert JSON String to Java Map with Jackson
March 16, 2023 - String json = "{\n" + "\"Task 1\" : \"In_Progress\",\n" + "\"Task 2\" : \"Done\",\n" + "\"Task 3\" : \"Planned\"\n" + "}"; // ObjectMapper instantiation ObjectMapper objectMapper = new ObjectMapper(); // Deserialization into a Map Map<String, TASK_STATUS> result = objectMapper.readValue(json, HashMap.class); // Printing the results System.out.println(result.entrySet()); We've chucked the json contents into the readValue() method, and since it contains JSON that can be deserialized into a Map, given the key-value pairings, told Jackson to deserialize into a HashMap.
๐ŸŒ
Java Guides
javaguides.net โ€บ 2023 โ€บ 10 โ€บ convert-json-string-to-map-in-java.html
Convert JSON string to Map in Java
October 26, 2023 - import com.fasterxml.jackson.databind.ObjectMapper; import java.util.Map; public class MainApp { public static void main(String[] args) { // Sample JSON string String jsonStr = "{\"id\":1,\"name\":\"Jane Smith\",\"email\":\"jane.smith@example.com\"}"; // Create an ObjectMapper instance ObjectMapper mapper = new ObjectMapper(); try { // Convert JSON string to Map Map<String, Object> map = mapper.readValue(jsonStr, Map.class); // Display the map for (Map.Entry<String, Object> entry : map.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } } catch (Exception e) { e.printStackTrace(); } } }
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 570738 โ€บ java โ€บ Convert-String-Map
Convert String to Map (Java in General forum at Coderanch)
March 18, 2012 - Here i have to split this whole String "a" into broken tokens like a=100,b=200,c=300 so have used split method and now have to seperate the key and values like key:a and value:100.should not use StringTokenizer but can use any other collection like HashMap,HashTable.etc.I dont know how to add ...
Top answer
1 of 2
2

One simple way is to use str_to_map function after you get rid of the double quotes from PersonalInfo column:

val df1 = df.withColumn(
  "PersonalInfo",
  expr("str_to_map(regexp_replace(PersonalInfo, '\"', ''))")
)

df1.show(false)

//+-------+-------+------------------------------------------------------------------------------+
//|Empcode|EmpName|PersonalInfo                                                                  |
//+-------+-------+------------------------------------------------------------------------------+
//|1      |abc    |{email -> abc@gmail.com, Location -> India, Gender -> Male}                   |
//|2      |xyz    |{email -> xyz@gmail.com, Location -> US}                                      |
//|3      |pqr    |{email -> abc@gmail.com, Gender -> Female, Location -> Europe, Mobile -> 1234}|
//+-------+-------+------------------------------------------------------------------------------+
2 of 2
1

If you want to create a map from PersonalInfo column, from Spark 3.0 you can proceed as follows:

  • Split your string according to "","" using split function
  • For each element of your obtained string array, create sub-arrays according to "":"" using split function
  • Remove all "" from elements of sub-arrays using regexp_replace function
  • Build map entries using struct function
  • Use map_from_entries to build map from your array of entries

Complete code is as follows:

import org.apache.spark.sql.functions.{col, map_from_entries, regexp_replace, split, struct, transform}

val result = data.withColumn("PersonalInfo",
  map_from_entries(
    transform(
      split(col("PersonalInfo"), "\"\",\"\""),
      item => struct(
        regexp_replace(split(item, "\"\":\"\"")(0), "\"\"", ""),
        regexp_replace(split(item, "\"\":\"\"")(1), "\"\"", "")
      )
    )
  )
)

With the following input_dataframe:

+-------+-------+---------------------------------------------------------------------------------------------+
|Empcode|EmpName|PersonalInfo                                                                                 |
+-------+-------+---------------------------------------------------------------------------------------------+
|1      |abc    |""email"":""abc@gmail.com"",""Location"":""India"",""Gender"":""Male""                       |
|2      |xyz    |""email"":""xyz@gmail.com"",""Location"":""US""                                              |
|3      |pqr    |""email"":""abc@gmail.com"",""Gender"":""Female"",""Location"":""Europe"",""Mobile"":""1234""|
+-------+-------+---------------------------------------------------------------------------------------------+

You get the following result dataframe:

+-------+-------+------------------------------------------------------------------------------+
|Empcode|EmpName|PersonalInfo                                                                  |
+-------+-------+------------------------------------------------------------------------------+
|1      |abc    |{email -> abc@gmail.com, Location -> India, Gender -> Male}                   |
|2      |xyz    |{email -> xyz@gmail.com, Location -> US}                                      |
|3      |pqr    |{email -> abc@gmail.com, Gender -> Female, Location -> Europe, Mobile -> 1234}|
+-------+-------+------------------------------------------------------------------------------+