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.
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}|
+-------+-------+------------------------------------------------------------------------------+
🌐
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 ...
🌐
Coderanch
coderanch.com › t › 425284 › java › convert-hashmap-string-anytype-hashMap
convert hashmap <string, anytype > to hashMap<string, object> (Java in General forum at Coderanch)
Can somebody help me to convert any type of "values" , might be integer,string .. To object I want to keep the key as same and want to convert the value as object thanks zuje ... Anything that is not a primitive is already an Object. Therefore, Map<String,Integer> is a Map<? extends String,? extends Object>, and you can use it in the putAll method: Also, most Map implementation classes have a constructor that takes a Map<? extends K,? extends V> so it's even shorter for only one map: