How to parse a string which is in particular format into HashMap?

Viewed 191

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.

1 Answers

Use a regex to ensure that the incoming payload string has the correct format:

public static Map<String, String> parseStringToMap(String payload) {
    Map<String, String> map = new HashMap<>();
    if (!payload.matches("[A-Za-z0-9]+=[A-Za-z0-9]+(\\|[A-Za-z0-9]+=[A-Za-z0-9]+)*")) {
        // return empty map
        return map;
    }

    // your original code here
}

With regard to your concern about the same key appearing more than once, the default behavior of a hashmap would be to overwrite, so you might already be covered in this case. Just write your key/value pairs as they arise and you will automatically be overwriting old values with the new ones.

Related