Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
414 views
in Technique[技术] by (71.8m points)

java - 如何使用流或其他更好的方法来解析字符串?(How to parse strings using streams or other better way?)

I have a HashMap and I want to convert data in it to a Response object.

(我有一个HashMap,我想将其中的数据转换为Response对象。)

Is it possible to achieve the code below that parses the string in a better and optimized and cleaner way?

(是否有可能实现下面的代码,从而以更好,优化和更清洁的方式解析字符串?)

May be 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
  ask by tech_ques translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I can't see any significant improvements.

(我看不到任何重大改进。)

There are a couple of minor points:

(有几点要点:)

  1. The regex doesn't need to test for a sign.

    (正则表达式不需要测试符号。)

    You are already splitting on a - character, so a minus sign in the number field is not possible.

    (您已经在-字符上进行了拆分,因此不可能在数字字段中使用减号。)

  2. The test

    (考试)

     if(str.length == 3){ 

    could be

    (可能)

     else if(str.length == 3){ 

There are numerous style errors in the code, and I spotted a couple of compilation errors.

(代码中有很多样式错误,我发现了一些编译错误。)

You should have corrected them before you asked us to help with your code.

(要求我们提供代码帮助之前,您应该已经对它们进行了纠正。)

Finally, streams won't help with this task.

(最后,流将无法完成此任务。)

They certainly won't make it more efficient.

(他们当然不会提高效率。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...