I have a HashMap and I want to convert data in it to a Response object. Is it possible to achieve this code that parses the string in a better and optimized and cleaner way, maybe by using streams?
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<FinalProduct> products = new ArrayList<>();
for(String key : map.keySet()){
FinalProduct response = new FinalProduct();
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];
products.add(response);
}
}
}
class FinalProduct{
String id;
String city;
Long code;
String client;
String type;
Long qty;
// getters and setters
}
if(str.matches("-?\\d+(\\.\\d+)?");){this code does not compile. \$\endgroup\$