33

How can I convert a String into a HashMap?

String value = "{first_name = naresh, last_name = kumar, gender = male}"

into

Map<Object, Object> = {
    first_name = naresh,
    last_name = kumar,
    gender = male
}

Where the keys are first_name, last_name and gender and the values are naresh, kumar, male.

Note: Keys can be any thing like city = hyderabad.

I am looking for a generic approach.

7
  • Extract the "key, value" pairs from the String and create the map. Commented Oct 21, 2014 at 11:51
  • 1
    Did you try anything ? Commented Oct 21, 2014 at 11:51
  • 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 Commented Oct 21, 2014 at 11:52
  • This works when I know what key is exactly and how many keys are there,but if I have like 10 keys in String. Commented Oct 21, 2014 at 11:52
  • 1
    I tried convert the same using mapper.readValue(input,new TypeReference<Map<Object, Object>>() {}) from jackson library but raised ParseException Commented Oct 21, 2014 at 11:55

9 Answers 9

67

This is one solution. If you want to make it more generic, you can use the StringUtils library.

String value = "{first_name = naresh,last_name = kumar,gender = male}";
value = value.substring(1, value.length()-1);           //remove curly brackets
String[] keyValuePairs = value.split(",");              //split the string to creat key-value pairs
Map<String,String> map = new HashMap<>();               

for(String pair : keyValuePairs)                        //iterate over the pairs
{
    String[] entry = pair.split("=");                   //split the pairs to get key and value 
    map.put(entry[0].trim(), entry[1].trim());          //add them to the hashmap and trim whitespaces
}

For example you can switch

 value = value.substring(1, value.length()-1);

to

 value = StringUtils.substringBetween(value, "{", "}");

if you are using StringUtils which is contained in apache.commons.lang package.

Sign up to request clarification or add additional context in comments.

5 Comments

Provide answer in full is kill the OP's chance of learning. This is not helping him but encourage OP to ask same kind of question again.
Sorry for that, but my intention here was,if I dont know what are keys in string.
You dont have to know the keys. My code always uses the left side of the equal sign as the key. Did you tried it?
It would break if there is any comma in the key or value. Should consider that as well.
value = StringUtils.substringBetween(value, "{", "}"); Should not be used when value is a json string
11

In a single line you can convert any type of object to any other type of object.

(Since I use Gson quite liberally, I am sharing a Gson based approach)

Gson gson = new Gson();    
Map<Object,Object> attributes = gson.fromJson(gson.toJson(value),Map.class);

What it does is:

  1. gson.toJson(value) will serialize your object into its equivalent Json representation.
  2. gson.fromJson will convert the Json string to specified object. (in this example - Map)

There are 2 advantages with this approach:

  1. The flexibility to pass any Object instead of String to toJson method.
  2. You can use this single line to convert to any object even your own declared objects.

Comments

6
String value = "{first_name = naresh,last_name = kumar,gender = male}"

Let's start

  1. Remove { and } from the String>>first_name = naresh,last_name = kumar,gender = male
  2. Split the String from ,>> array of 3 element
  3. Now you have an array with 3 element
  4. Iterate the array and split each element by =
  5. Create a Map<String,String> put each part separated by =. first part as Key and second part as Value

5 Comments

Maybe trim the String to not get confused when calling map.get(trimmedString)
@Nareshkumar There is no issue with that.
+1 for showing the way, but not spoon feeding the code
spliting by comma isn't right, what if map = {num = "12,12,2016" , name = blabla}
@user5980143 then you have to come up with a different strategy.
0
@Test
public void testToStringToMap() {
    Map<String,String> expected = new HashMap<>();
    expected.put("first_name", "naresh");
    expected.put("last_name", "kumar");
    expected.put("gender", "male");
    String mapString = expected.toString();
    Map<String, String> actual = Arrays.stream(mapString.replace("{", "").replace("}", "").split(","))
            .map(arrayData-> arrayData.split("="))
            .collect(Collectors.toMap(d-> ((String)d[0]).trim(), d-> (String)d[1]));

    expected.entrySet().stream().forEach(e->assertTrue(actual.get(e.getKey()).equals(e.getValue())));
}

2 Comments

Map toString consider casting map as per requirement this way convert map toString back to Map
Comments are not for adding this type of clarifications to own posts - please add this to your answer, and remove the comment.
0

try this out :)

public static HashMap HashMapFrom(String s){
    HashMap base = new HashMap(); //result
    int dismiss = 0; //dismiss tracker
    StringBuilder tmpVal = new StringBuilder(); //each val holder
    StringBuilder tmpKey = new StringBuilder(); //each key holder

    for (String next:s.split("")){ //each of vale
        if(dismiss==0){ //if not writing value
            if (next.equals("=")) //start writing value
                dismiss=1; //update tracker
            else
                tmpKey.append(next); //writing key
        } else {
            if (next.equals("{")) //if it's value so need to dismiss
                dismiss++;
            else if (next.equals("}")) //value closed so need to focus
                dismiss--;
            else if (next.equals(",") //declaration ends
                    && dismiss==1) {
                //by the way you have to create something to correct the type
                Object ObjVal = object.valueOf(tmpVal.toString()); //correct the type of object
                base.put(tmpKey.toString(),ObjVal);//declaring
                tmpKey = new StringBuilder();
                tmpVal = new StringBuilder();
                dismiss--;
                continue; //next :)
            }
            tmpVal.append(next); //writing value
        }
    }
    Object objVal = object.valueOf(tmpVal.toString()); //same as here
    base.put(tmpKey.toString(), objVal); //leftovers
    return base;
}

examples input : "a=0,b={a=1},c={ew={qw=2}},0=a" output : {0=a,a=0,b={a=1},c={ew={qw=2}}}

3 Comments

It's better to add an explanation of your code in order to improve your answer.
I'm bad in explaining 😅 , but i think it can be recognized
Keep in mind you should deal with this type of string -> "{a={a={a=[a,b,c],b=c},c=0}}"
0

Should Use this way to convert into map :

    String student[] = students.split("\\{|}");
    String id_name[] = student[1].split(",");

    Map<String,String> studentIdName = new HashMap<>();

    for (String std: id_name) {
        String str[] = std.split("=");
        studentIdName.put(str[0],str[1]);
  }

Comments

0
You can use below library to convert any string to Map object.


<!-- https://mvnrepository.com/artifact/io.github.githubshah/gsonExtension -->
<dependency>
    <groupId>io.github.githubshah</groupId>
    <artifactId>gsonExtension</artifactId>
    <version>4.1.0</version>
</dependency>

1 Comment

can you provide an example how this works?
0

Suprised noone has mentioned just using JSONObject(org.json.JSONObject)

        JSONObject json = new JSONObject(mapStr);
        Map<String,Object> map = json.toMap();

Far better than writing your own parser?

1 Comment

This converts the data to bytes
0

Using Java 8 Stream:

Map<String, String> map = Arrays.stream(value.replaceAll("[{}]", " ").split(","))
                .map(s -> s.split("=", 2))
                .collect(Collectors.toMap(s -> s[0].trim(), s -> s[1].trim()));
  1. Arrays.stream() to convert string array to stream.
  2. replaceAll("[{}]", " "): regex version to replace both braces.
  3. split(","): Split the string by , to get individual map entries.
  4. s.split("=", 2): Split them by = to get the key and the value and ensure that the array is never larger than two elements.
  5. The collect() method in Stream API collects all objects from a stream object and stored in the type of collection.
  6. Collectors.toMap(s -> s[0].trim(), s -> s[1].trim()): Accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.