Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string to a HashMap? [duplicate]

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 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); 
like image 793
Bishan Avatar asked May 09 '12 10:05

Bishan


People also ask

Can HashMap value be duplicated?

Duplicates: HashSet doesn't allow duplicate values. HashMap stores key, value pairs and it does not allow duplicate keys.

Can we convert string to HashMap in Java?

In order to convert strings to HashMap, the process is divided into two parts: The input string is converted to an array of strings as output. Input as an array of strings is converted to HashMap.

How do I store duplicate keys on a Map?

You can use a TreeMap with a custom Comparator in order to treat each key as unequal to the others. It would also preserve the insertion order in your map, just like a LinkedHashMap. So, the net result would be like a LinkedHashMap which allows duplicate keys!


1 Answers

You can do that with Guava's Splitter.MapSplitter:

Map<String, String> properties = Splitter.on(",")     .withKeyValueSeparator(":")     .split(inputString); 
like image 187
KARASZI István Avatar answered Sep 28 '22 15:09

KARASZI István