What's the best way to build a string of delimited items in Java?

前端 未结 30 2494
耶瑟儿~
耶瑟儿~ 2020-11-22 05:36

While working in a Java app, I recently needed to assemble a comma-delimited list of values to pass to another web service without knowing how many elements there would be i

30条回答
  •  萌比男神i
    2020-11-22 06:33

    Why don't you do in Java the same thing you are doing in ruby, that is creating the delimiter separated string only after you've added all the pieces to the array?

    ArrayList parms = new ArrayList();
    if (someCondition) parms.add("someString");
    if (anotherCondition) parms.add("someOtherString");
    // ...
    String sep = ""; StringBuffer b = new StringBuffer();
    for (String p: parms) {
        b.append(sep);
        b.append(p);
        sep = "yourDelimiter";
    }
    

    You may want to move that for loop in a separate helper method, and also use StringBuilder instead of StringBuffer...

    Edit: fixed the order of appends.

提交回复
热议问题