如何将字符串转换为 HashMap?

How to convert a string to a HashMap?(如何将字符串转换为 HashMap?)

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

问题描述

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

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?

基础教程推荐