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");
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 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);
You can do that with Guava's Splitter.MapSplitter:
for more info click here
Use the
String.split()
method with the,
separator to get the list of pairs. Iterate the pairs and usesplit()
again with the:
separator to get the key and value for each pair.Assuming no key contains either
','
or':'
: