Converts data in a HashMap to a custom object I have a HashMap and I want to convert data in it to a Response object, but I do not find it clean and optimized. Is there a better way to achieve this?

class Converter{

   public static void main(String[] args) {

      Map&lt;String, Long&gt; map = new HashMap&lt;String, Long&gt;();
      map.put("111", 80) // first 
      map.put("1A9|ppp", 190) // second
      map.put("98U|6765", 900) // third
      map.put("999|aa|local", 95) // fourth

      List&lt;Response&gt; responses = new ArrayList&lt;&gt;();
      for(String key : map.keySet()){
        Response response = new Response();
        String[] str  = key.split("\\|");
        response.id = str[0] //id is always present in key i.e 111, 1A9, 98U,999
        if(str.length == 2) {
             if(str.matches("-?\\d+(\\.\\d+)?");){ // check if is numeric
                  response.code = str[1]; // 6765
             }
             else{
                  response.city = str[1]; //ppp
             }
        }
         if(str.length == 3){
                  response.client = str[1]; //aa
                  response.type = str[2];   // local
         } 
        response.qty = map.get[key];
        responses.add(response);
      }
   }
}


class Response{

String id;
String city;
Long code;
String client;
String type;
Long qty;
// getters and setters

}
As dustytrash already mentioned in a comment, it would be much more sensible to simply use the Response object as the map key and be done.

If this is not possible due to unknown external constraints, move the translation to and from String into the Response object.

class Response {
    public static Response fromString(String s) {
        // ... do the parsing here
    }

    @Override
    public String toString() {
        // generate "98U|6765" or whatever
        // debatable: maybe don't use the overridden toString for the technical representation
    }
}


This encapsulates the nitty-gritty details of conversion in the class itself.

The converson then boils down to

map.keySet().stream()
    .map(Response::fromString)
    .collect(Collectors.toList());