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:
-
gson.toJson(value)
will serialize your object into its equivalent Json representation. -
gson.fromJson
will convert the Json string to specified object. (in this example -Map
)
There are 2 advantages with this approach:
- The flexibility to pass an Object instead of String to
toJson
method. - 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
- Remove
{
and}
from theString
>>first_name = naresh,last_name = kumar,gender = male - Split the
String
from,
>> array of 3 element - Now you have an
array
with3
element - Iterate the
array
and split each element by=
- Create a
Map<String,String>
put each part separated by=
. first part asKey
and second part asValue
![Naresh kumar](https://i.stack.imgur.com/1zNqc.jpg?s=256&g=1)
Comments
-
Naresh kumar over 3 years
How can I convert a
String
into aHashMap
?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
andgender
and the values arenaresh
,kumar
,male
.Note: Keys can be any thing like
city = hyderabad
.I am looking for a generic approach.
-
user over 9 yearsMaybe trim the String to not get confused when calling map.get(trimmedString)
-
Ruchira Gayan Ranaweera over 9 yearsProvide 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 over 9 years@Nareshkumar There is no issue with that.
-
ifloop over 9 years+1 for showing the way, but not spoon feeding the code
-
Naresh kumar over 9 yearsSorry for that, but my intention here was,if I dont know what are keys in string.
-
kai over 9 yearsYou 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 over 7 yearsspliting by comma isn't right, what if map = {num = "12,12,2016" , name = blabla}
-
Ruchira Gayan Ranaweera over 7 years@user5980143 then you have to come up with a different strategy.
-
Admin almost 6 yearsMap toString consider casting map as per requirement this way convert map toString back to Map
-
desertnaut almost 6 yearsComments are not for adding this type of clarifications to own posts - please add this to your answer, and remove the comment.
-
KumarAnkit over 5 yearsIt would break if there is any comma in the key or value. Should consider that as well.
-
Purushothaman over 5 yearsvalue = StringUtils.substringBetween(value, "{", "}"); Should not be used when value is a json string
-
DobromirM about 5 yearsIt's better to add an explanation of your code in order to improve your answer.
-
Admin about 5 yearsI'm bad in explaining 😅 , but i think it can be recognized
-
Admin about 5 yearsKeep in mind you should deal with this type of string -> "{a={a={a=[a,b,c],b=c},c=0}}"