0

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;
5
  • I think yes, why not. You just have to write a convert method. Commented Oct 28, 2013 at 10:27
  • 1
    What does the String look like? Commented Oct 28, 2013 at 10:27
  • It would help if you provide a sample string that was constructed from the Map. Commented Oct 28, 2013 at 10:29
  • It works with LinkedHashMap, as the order is preserved and you will end up with same LinkedHashMap when converted from the string. If it was HashMap, I think that you might end up with a different map. Commented Oct 28, 2013 at 10:35
  • I think there is no standard approach to reconstruct the map from the string returned by toString (other than approach you have given). What is your use case? Can't you just serialize the map and deserialize it later? Commented Oct 28, 2013 at 10:35

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Yea the string looks like that
Note, though, that semicolons or equals signs in keys or values won't be escaped, so some maps won't be convertible.
0

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

2 Comments

Because in Android, when you pass a serializable LinkedHashMap thats in order, it messes it up and converts it to a HashMap :(
It wouldn't hurt to add that to the question!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.