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);
try
You can also use JSONObject class from json.org to this will convert your HashMap to JSON string which is well formatted
Example:
result:
Your can also get key from it like
result:
Use StringTokenizer to parse the string.
You can to use split to do it:
Nevertheless, myself I will go for guava based solution. https://stackoverflow.com/a/10514513/1356883
In one line :
Details:
1) Split entry pairs and convert string array to
List<String>
in order to usejava.lang.Collection.Stream
API fromJava 1.8
2) Map the resulting string list
"key:value"
to a string array with [0] as key and [1] as value3) Use
collect
terminal method from stream API to mutate4) Use the
Collectors.toMap()
static method which take two Function to perform mutation from input type to key and value type.where T is the input type, K the key type and U the value type.
5) Following lambda mutate
String
toString
key andString
toInteger
valueEnjoy the stream and lambda style with
Java 8
. No more loops !I recommend using
com.fasterxml.jackson.databind.ObjectMapper
(Maven repo link: https://mvnrepository.com/artifact/com.fasterxml.jackson.core) like