user3360031
user3360031

Reputation: 627

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.

Upvotes: 1

Views: 1410

Answers (3)

Sibin Muhammed A R
Sibin Muhammed A R

Reputation: 1

Using Java Stream:

public static void main(String[] args) throws Exception {

    String value = "{id=1111, company=A Sample Company}";
    Map<String, String> map = Arrays.stream(value.replaceAll("[{}]", " ").split(","))
            .map(s -> s.split("=", 2))
            .collect(Collectors.toMap(s -> s[0].trim(), s -> s[1].trim()));
    System.out.println(map);
}

O/P: {company=A Sample Company, id=1111}

Upvotes: 0

Gaurav
Gaurav

Reputation: 821

You can use Guava'a splitter (com.google.common.base.Splitter) https://code.google.com/p/guava-libraries/

String s = "{id=1111, company=A Sample Company}";
String stringWithoutBracket = s.substring(1, s.length() - 1);
Map<String, String> properties = Splitter.on(",").withKeyValueSeparator("=").split(stringWithoutBracket);

Upvotes: 1

TheLostMind
TheLostMind

Reputation: 36304

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}

Upvotes: 1

Related Questions