String to HashMap JAVA

2020-01-30 03:49发布

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");

then

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

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);

10条回答
聊天终结者
2楼-- · 2020-01-30 04:48

You can do that with Guava's Splitter.MapSplitter:

Map<String, String> properties = Splitter.on(",").withKeyValueSeparator(":").split(inputString);
查看更多
Fickle 薄情
3楼-- · 2020-01-30 04:49
 String mapString=hasmap.toString();

 Pattern p = Pattern.compile("[\\{\\}\\=\\, ]++");

 String[] split = p.split(mapString);

for more info click here

查看更多
smile是对你的礼貌
4楼-- · 2020-01-30 04:51

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]));
}
查看更多
劳资没心,怎么记你
5楼-- · 2020-01-30 04:53

Assuming no key contains either ',' or ':':

Map<String, Integer> map = new HashMap<String, Integer>();
for(final String entry : s.split(",")) {
    final String[] parts = entry.split(":");
    assert(parts.length == 2) : "Invalid entry: " + entry;
    map.put(parts[0], new Integer(parts[1]));
}
查看更多
登录 后发表回答