How to convert String into Hashmap in java

120,855

Solution 1

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.

Solution 2

You can do it in single line, for any object type not just Map.

(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 an Object instead of String to toJson method.
  2. You can use this single line to convert to any object even your own declared objects.

Solution 3

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
Share:
120,855
Naresh kumar
Author by

Naresh kumar

Amm....

Updated on January 31, 2021

Comments

  • Naresh kumar
    Naresh kumar over 3 years

    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.

  • user
    user over 9 years
    Maybe trim the String to not get confused when calling map.get(trimmedString)
  • Ruchira Gayan Ranaweera
    Ruchira Gayan Ranaweera over 9 years
    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.
  • Ruchira Gayan Ranaweera
    Ruchira Gayan Ranaweera over 9 years
    @Nareshkumar There is no issue with that.
  • ifloop
    ifloop over 9 years
    +1 for showing the way, but not spoon feeding the code
  • Naresh kumar
    Naresh kumar over 9 years
    Sorry for that, but my intention here was,if I dont know what are keys in string.
  • kai
    kai over 9 years
    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?
  • dina
    dina over 7 years
    spliting by comma isn't right, what if map = {num = "12,12,2016" , name = blabla}
  • Ruchira Gayan Ranaweera
    Ruchira Gayan Ranaweera over 7 years
    @user5980143 then you have to come up with a different strategy.
  • Admin
    Admin almost 6 years
    Map toString consider casting map as per requirement this way convert map toString back to Map
  • desertnaut
    desertnaut almost 6 years
    Comments are not for adding this type of clarifications to own posts - please add this to your answer, and remove the comment.
  • KumarAnkit
    KumarAnkit over 5 years
    It would break if there is any comma in the key or value. Should consider that as well.
  • Purushothaman
    Purushothaman over 5 years
    value = StringUtils.substringBetween(value, "{", "}"); Should not be used when value is a json string
  • DobromirM
    DobromirM about 5 years
    It's better to add an explanation of your code in order to improve your answer.
  • Admin
    Admin about 5 years
    I'm bad in explaining 😅 , but i think it can be recognized
  • Admin
    Admin about 5 years
    Keep in mind you should deal with this type of string -> "{a={a={a=[a,b,c],b=c},c=0}}"