I have the following string:
JavaScript
x
{id=1111, company=A Sample Company}
I want to convert it back to hashmap. I tried the following code below
JavaScript
protected HashMap<String,String> convertToStringToHashMap(String text){
HashMap<String,String> data = new HashMap<String,String>();
Pattern p = Pattern.compile("[\{\}\=\, ]++");
String[] split = p.split(text);
for ( int i=1; i+2 <= split.length; i+=2 ){
data.put( split[i], split[i+1] );
}
return data;
}
but the problem is that it can’t convert the string with spaces. It outputs something like this:
JavaScript
{id=1111, company=A, Sample=Company}
I think it has something to do with the regex. Help! Thanks.
Advertisement
Answer
Something like this will work for you :
JavaScript
public static void main(String[] args) {
String s = "{id=1111, company=A Sample Company}";
s=s.replaceAll("\{|\}", "");
Map<String, String> hm = new HashMap<String, String>();
String[] entrySetValues = s.split(",");
for(String str : entrySetValues){
String[] arr = str.trim().split("=");
hm.put(arr[0], arr[1]);
}
System.out.println(hm);
}
{id=1111, company=A Sample Company}