如何将字符串转换为HashMap? [英] How to convert a string to a HashMap?

查看:124
本文介绍了如何将字符串转换为HashMap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java属性文件,并且有一个 KEY 作为 ORDER .因此,在加载如下所示的属性文件后,我使用 getProperty()方法检索了该 KEY VALUE .

I have a Java Property file and there is a KEY as ORDER. So I retrieve the VALUE of that KEY using the getProperty() method after loading the property file like below.:

String s = prop.getProperty("ORDER");

然后

s ="SALES:0,SALE_PRODUCTS:1,EXPENSES:2,EXPENSES_ITEMS:3";

我需要从上面的字符串创建一个HashMap. SALES,SALE_PRODUCTS,EXPENSES,EXPENSES_ITEMS 应该是HashMap的 KEY 0、1、2、3,应该是 VALUE KEY s的code> s.

I need to create a HashMap from above string. SALES,SALE_PRODUCTS,EXPENSES,EXPENSES_ITEMS should be KEY of HashMap and 0,1,2,3, should be VALUEs of KEYs.

如果使用硬线连接,则如下所示:

If it's hard corded, it seems like below:

Map<String, Integer> myMap  = new HashMap<String, Integer>();
myMap.put("SALES", 0);
myMap.put("SALE_PRODUCTS", 1);
myMap.put("EXPENSES", 2);
myMap.put("EXPENSES_ITEMS", 3);

推荐答案

使用

Use the String.split() method with the , separator to get the list of pairs. Iterate the pairs and use split() again with the : separator to get the key and value for each pair.

Map<String, Integer> myMap = new HashMap<String, Integer>();
String s = "SALES:0,SALE_PRODUCTS:1,EXPENSES:2,EXPENSES_ITEMS:3";
String[] pairs = s.split(",");
for (int i=0;i<pairs.length;i++) {
    String pair = pairs[i];
    String[] keyValue = pair.split(":");
    myMap.put(keyValue[0], Integer.valueOf(keyValue[1]));
}

这篇关于如何将字符串转换为HashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆