本文介绍了java中如何将String转换成Hashmap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将 String
转换为 HashMap
?
String value = "{first_name = naresh, last_name = kumar, gender = male}"
进入
Map<Object, Object> = {
first_name = naresh,
last_name = kumar,
gender = male
}
其中键是 first_name
、last_name
和 gender
,值是 naresh
、kumar
, 男性
.
Where the keys are first_name
, last_name
and gender
and the values are naresh
, kumar
, male
.
注意:键可以是任何东西,例如 city = hyderabad
.
Note: Keys can be any thing like city = hyderabad
.
我正在寻找一种通用的方法.
I am looking for a generic approach.
推荐答案
这是一种解决方案.如果你想让它更通用,你可以使用 StringUtils
库.
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
}
比如你可以切换
value = value.substring(1, value.length()-1);
到
value = StringUtils.substringBetween(value, "{", "}");
如果您正在使用 apache.commons.lang
包中包含的 StringUtils
.
if you are using StringUtils
which is contained in apache.commons.lang
package.
这篇关于java中如何将String转换成Hashmap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!