本文介绍了字符串到HashMap JAVA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Java属性文件,并且有一个 KEY 作为 ORDER 。所以我在加载属性文件后使用getProperty()方法检索 VALUE KEY

I have Java Property file and there is a KEY as ORDER. so I retrieve VALUE of that KEY using getProperty() method after load property file as below.

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

然后

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

我需要从上面的字符串创建一个HashMap。 销售,SALE_PRODUCTS,费用,EXPENSES_ITEMS 应该是HashMap的 KEY 0,1,2 ,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.

如果硬线,似乎如下。

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


推荐答案

使用方法与分隔符来获取对的列表。迭代对,并使用分隔符再次使用 split()来获取每对的键和值。 / p>

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 JAVA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 23:53