I have a Java Property file and there is a KEY
as ORDER
. So I retrieve the VALUE
of that KEY
using the getProperty(
You can also use JSONObject class from json.org to this will convert your HashMap to JSON string which is well formatted
Example:
Map<String,Object> map = new HashMap<>();
map.put("myNumber", 100);
map.put("myString", "String");
JSONObject json= new JSONObject(map);
String result= json.toString();
System.out.print(result);
result:
{'myNumber':100, 'myString':'String'}
Your can also get key from it like
System.out.print(json.get("myNumber"));
result:
100
Assuming no key contains either ','
or ':'
:
Map<String, Integer> map = new HashMap<String, Integer>();
for(final String entry : s.split(",")) {
final String[] parts = entry.split(":");
assert(parts.length == 2) : "Invalid entry: " + entry;
map.put(parts[0], new Integer(parts[1]));
}
Use StringTokenizer to parse the string.
String s ="SALES:0,SALE_PRODUCTS:1,EXPENSES:2,EXPENSES_ITEMS:3";
Map<String, Integer> lMap=new HashMap<String, Integer>();
StringTokenizer st=new StringTokenizer(s, ",");
while(st.hasMoreTokens())
{
String [] array=st.nextToken().split(":");
lMap.put(array[0], Integer.valueOf(array[1]));
}
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]));
}
You can do that with Guava's Splitter.MapSplitter:
Map<String, String> properties = Splitter.on(",").withKeyValueSeparator(":").split(inputString);
You can to use split to do it:
String[] elements = s.split(",");
for(String s1: elements) {
String[] keyValue = s1.split(":");
myMap.put(keyValue[0], keyValue[1]);
}
Nevertheless, myself I will go for guava based solution. https://stackoverflow.com/a/10514513/1356883