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

前端 未结 30 2202
耶瑟儿~
耶瑟儿~ 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:17

    Your approach is not too bad, but you should use a StringBuffer instead of using the + sign. The + has the big disadvantage that a new String instance is being created for each single operation. The longer your string gets, the bigger the overhead. So using a StringBuffer should be the fastest way:

    public StringBuffer appendWithDelimiter( StringBuffer original, String addition, String delimiter ) {
            if ( original == null ) {
                    StringBuffer buffer = new StringBuffer();
                    buffer.append(addition);
                    return buffer;
            } else {
                    buffer.append(delimiter);
                    buffer.append(addition);
                    return original;
            }
    }
    

    After you have finished creating your string simply call toString() on the returned StringBuffer.

提交回复
热议问题