如何在Java中将String转换为Hashmap [英] How to convert String into Hashmap in java
本文介绍了如何在Java中将String转换为Hashmap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将字符串
转换为 HashMap
?
String value = "{first_name = naresh, last_name = kumar, gender = male}"
进入
Map<Object, Object> = {
first_name = naresh,
last_name = kumar,
gender = male
}
键是姓氏
,姓氏
和性别
的值是 naresh
, kumar
, male
。
注意:键可以是 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, "{", "}");
如果使用的是<$ c $中包含的 StringUtils
$ c> apache.commons.lang 包。
if you are using StringUtils
which is contained in apache.commons.lang
package.
这篇关于如何在Java中将String转换为Hashmap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文