I have a String which is coming in particular format so I want to parse that string into map. I have a below method which parses String to a Map and it works fine.
public static Map<String, String> parseStringToMap(String payload) {
Map<String, String> map = new HashMap<>();
try {
for (String part : payload.split("\\|")) {
String[] subparts = part.split("=", 2);
map.put(subparts[0], subparts[1]);
}
} catch (Exception ex) {
}
return map;
}
Sample example of a string:
"type=3|Id=23456|user=13456"
"type=3|Id=23456|user=13456|type=3"
It might be possible that same key can appear many times in the same string payload so I need to overwrite the value for that key in my mutable map.
Also if my string payload is not in this below format then I would like to return empty map back. My string format will always be like this and if it is not in this format then I would return empty map back. Right now I am not sure how can I add this logic so that I can return empty map if this case arises?
"a=b|c=d|e=f"
I am working with Java 7. What is the best and efficient way to do this?
My spec is this only. My String will always be in this format:
"a=b|c=d|e=f"
It will never starts with any special character.