如何使用流或其他更好的方法来解析字符串?

时间:2019-11-30 14:55:00

标签: java regex java-stream

我有一个HashMap,我想将其中的数据转换为Response对象。是否有可能实现下面的代码,从而以更好,优化和更清洁的方式解析字符串?可能正在使用流?

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

1 个答案:

答案 0 :(得分:0)

为了使您的代码可重用,建议您将FinalProduct构造函数创建为

FinalProduct(String key, Long value) {
    String[] str = key.split("-");
    this.id = str[0];
    if (str.length == 2) {
        if (str[1].matches("-?\\d+(\\.\\d+)?")) {
            this.code = Long.parseLong(str[1]);
        } else {
            this.city = str[1];
        }
    } else if (str.length == 3) {     // ELSE IF !!
        this.client = str[1];
        this.type = str[2];
    }
    this.qty = value;
}

然后您可以将其用作

List<FinalProduct> products = map.entrySet().stream()
                                 .map(e -> new FinalProduct(e.getKey(), e.getValue()))
                                 .collect(Collectors.toList());