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

前端 未结 30 2196
耶瑟儿~
耶瑟儿~ 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条回答
  • 2020-11-22 06:26

    Use an approach based on java.lang.StringBuilder! ("A mutable sequence of characters. ")

    Like you mentioned, all those string concatenations are creating Strings all over. StringBuilder won't do that.

    Why StringBuilder instead of StringBuffer? From the StringBuilder javadoc:

    Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

    0 讨论(0)
  • 2020-11-22 06:26

    So basically something like this:

    public static String appendWithDelimiter(String original, String addition, String delimiter) {
    
    if (original.equals("")) {
        return addition;
    } else {
        StringBuilder sb = new StringBuilder(original.length() + addition.length() + delimiter.length());
            sb.append(original);
            sb.append(delimiter);
            sb.append(addition);
            return sb.toString();
        }
    }
    
    0 讨论(0)
  • 2020-11-22 06:27

    You can generalize it, but there's no join in Java, as you well say.

    This might work better.

    public static String join(Iterable<? extends CharSequence> s, String delimiter) {
        Iterator<? extends CharSequence> iter = s.iterator();
        if (!iter.hasNext()) return "";
        StringBuilder buffer = new StringBuilder(iter.next());
        while (iter.hasNext()) buffer.append(delimiter).append(iter.next());
        return buffer.toString();
    }
    
    0 讨论(0)
  • 2020-11-22 06:29

    You can use Java's StringBuilder type for this. There's also StringBuffer, but it contains extra thread safety logic that is often unnecessary.

    0 讨论(0)
  • 2020-11-22 06:32

    Apache commons StringUtils class has a join method.

    0 讨论(0)
  • 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<String> parms = new ArrayList<String>();
    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.

    0 讨论(0)
提交回复
热议问题