2
\$\begingroup\$

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<String, Long> map = new HashMap<String, Long>();
 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<Response> responses = new ArrayList<>();
 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
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Nov 23, 2019 at 2:11
\$\endgroup\$
1
  • \$\begingroup\$ Why are you using a String to represent the response? Why not have a HashMap<Response, Long> \$\endgroup\$ Commented Nov 23, 2019 at 4:41

1 Answer 1

1
\$\begingroup\$

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());
answered Nov 23, 2019 at 6:36
\$\endgroup\$
2
  • \$\begingroup\$ Thank you. But i also wanted to know if there a way to improve parsing \$\endgroup\$ Commented Nov 24, 2019 at 18:30
  • \$\begingroup\$ And how to set the qty ? \$\endgroup\$ Commented Nov 24, 2019 at 18:44

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.