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
}
1 Answer 1
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());
-
\$\begingroup\$ Thank you. But i also wanted to know if there a way to improve parsing \$\endgroup\$Nishant– Nishant2019年11月24日 18:30:28 +00:00Commented Nov 24, 2019 at 18:30
-
\$\begingroup\$ And how to set the qty ? \$\endgroup\$Nishant– Nishant2019年11月24日 18:44:36 +00:00Commented Nov 24, 2019 at 18:44
HashMap<Response, Long>
\$\endgroup\$