Bishan Bishan - 1 month ago 5
Java Question

String to HashMap JAVA

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


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
VALUE
s of
KEY
s.

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

Answer

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