Convert java Map to custom key=value string

karolkpl picture karolkpl · Jan 16, 2014 · Viewed 18.5k times · Source

I have TreeMap<String,String> which I need to convert to URI-like string and then back to Map. I need to set custom delimiters.

Is there any tool (Guava, Apache commons?) that can do it for me? I know, I can write simple loops, but I'm looking for one-liner :)

For example

key    value
key1   val1
key2   val2

key1_val1|key2_val2

Answer

zapl picture zapl · Jan 16, 2014

According to David Tulig you could do it in guava via

 String string = Joiner.on("|").withKeyValueSeparator("_").join(map);

The opposite is also available via

 Map<String, String> map = Splitter.on("|").withKeyValueSeparator("_").split(string);