How to convert a string to a HashMap?(如何将字符串转换为 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, 应该是 VALUEKEYs.
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);
推荐答案
使用 String.split() 方法使用 , 分隔符来获取对列表.迭代这些对并再次使用 split() 和 : 分隔符来获取每对的键和值.
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将字符串转换为 HashMap?
基础教程推荐
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
