In general, you can't do this using the built in toString
method because it isn't doing anything to make the values parse-able, it's just trying to give you a representation that's helpful. As a particularly perverse example, consider the following code that demonstrates that two distinct maps can have the same printed representation:
import java.util.Map;
import java.util.TreeMap;
public class MapToStringExample {
public static void main(String[] args) {
Map<String,String> map1 = new TreeMap<>();
map1.put( "key1", "value1, key2=value2" );
System.out.println( "Map1: "+map1 );
Map<String,String> map2 = new TreeMap<>();
map2.put( "key1", "value1" );
map2.put( "key2", "value2" );
System.out.println( "Map2: "+map2 );
}
}
Map1: {key1=value1, key2=value2}
Map2: {key1=value1, key2=value2}
If you want to read in the printed representation of a Map like this, you'll either need to make some restrictions on what values you can put into it (e.g., nothing containing an =
or ,
), or you'll need to write your own output routine).
If you're looking to avoid rewriting code, you might look into the serialization API that would handler serializing and deserializing values for you. Of course, in this case, where you're just mapping strings to strings, all you need is a way to write alternating keys and values separated by some delimiter, and a way to escape that delimiter in the string representation (if it's allowed to appear in strings; if it's not, then you don't even need to escape it). That's not too hard of a serialization and deserialization task.