我有一个Java属性文件,并且有一个KEYas ORDER。因此VALUE,在加载如下所示的属性文件后,我KEY使用getProperty()方法检索的::
KEY
ORDER
VALUE
getProperty()
String s = prop.getProperty("ORDER");
然后
s ="SALES:0,SALE_PRODUCTS:1,EXPENSES:2,EXPENSES_ITEMS:3";
我需要从上面的字符串创建一个HashMap。SALES,SALE_PRODUCTS,EXPENSES,EXPENSES_ITEMS应该是KEYHashMap中,并0,1,2,3,应VALUE第KEY秒。
SALES,SALE_PRODUCTS,EXPENSES,EXPENSES_ITEMS
0,1,2,3,
如果是硬连线的,则如下所示:
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);
将该String.split()方法与,分隔符一起使用,以获取对列表。迭代对,然后split()再次使用:分隔符以获取每个对的键和值。
String.split()
,
split()
:
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])); }