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;
有帮助吗?

解决方案

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

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top