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);
Duplicates: HashSet doesn't allow duplicate values. HashMap stores key, value pairs and it does not allow duplicate keys.
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.
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!
You can do that with Guava's Splitter.MapSplitter:
Map<String, String> properties = Splitter.on(",") .withKeyValueSeparator(":") .split(inputString);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With