Skip to content
Advertisement

Convert String to Hashmap in Java

I have the following string:

{id=1111, company=A Sample Company}

I want to convert it back to hashmap. I tried the following code below

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:

{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 :

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}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement