Question

I have a String that has been constructed from another LinkedHashMap using toString method, and I want to do the reverse in creating another LinkedHashMap<String, String> with this String representation of the previous LinkedHashMap.

Is it possible withing using String splits and manually doing it in a loop calling LinkedHashMap.put() ?

I think this could work?

LinkedHashMap params = new LinkedHashMap();

String[] split = paramsString2.split(",");

for (int i = 0; i < split.length; i++) {
    String[] nameValue = split[i].split("=");
    params.put(nameValue[0], nameValue[1]);

}

return params;
Was it helpful?

Solution

Assume the string is of the form

key1=value1;key2=value2;key3=value3

Yes, it is possible. Use string.split(";") to separate the map entries into an array.

Then loop through the array, and for each entry, use string.split("=") to separate the key from the value.

Then add the key and value to the new LinkedHashMap:

String[] parts = entry.split("=");
map.put(parts[0], parts[1]);   //parts[0] is the key, parts[1] is the value

OTHER TIPS

Sure it is possible, but why should you do such horrible stuff?

Anyway, yes it is possible, you could also use the guava library to accomplish such a job. guava-library

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top