Skip to content
Advertisement

Java 8: How to convert String to Map?

I have a Map:

JavaScript

I converted it to a String:

JavaScript

How to convert utilMapString to Map in Java8? Who can help me with?

Advertisement

Answer

Split the string by , to get individual map entries. Then split them by = to get the key and the value.

JavaScript

Note: As pointed out by Andreas@ in the comments, this is not a reliable way to convert between a map and a string

EDIT: Thanks to Holger for this suggestion.

Use s.split("=", 2) to ensure that the array is never larger than two elements. This will be useful to not lose the contents (when the value has =)

Example: when the input string is "a=1,b=2,c=3=44=5555" you will get {a=1, b=2, c=3=44=5555}

Earlier (just using s.split("=")) will give {a=1, b=2, c=3}

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement