Search code examples
javacollectionshashmap

How to convert String into Hashmap in java


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.


Solution

  • 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.