java 如何把hashmap,如何在Java中将String转换为Hashmap

How can I convert a String into a HashMap?

String value = "{first_name = naresh, last_name = kumar, gender = male}"

into

Map = {

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.

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值