String.join() vs other string concatenation operations

后端 未结 3 1779
时光取名叫无心
时光取名叫无心 2021-01-01 18:20

I have quickly read over the Java8 String api documentation.

Now I am little curious about String.join() method to concat/join strings.

This kind of example

相关标签:
3条回答
  • 2021-01-01 18:28

    We can use StringJoiner (Java8+)

    import java.util.StringJoiner;
    
    public class StringJoinerTest {
    
    public static final String FILESEPARATOR = ", ";
    
    public static void main(String[] args) {
    
        StringJoiner sj = new StringJoiner(FILESEPARATOR);
        sj.add("Test1");
        sj.add("Test2");
        sj.add("Test3");
        System.out.println(sj);
       }
    }
    

    Output is

    Test1, Test2, Test3
    
    0 讨论(0)
  • 2021-01-01 18:43

    String.join relies on the class StringJoiner which itself relies on an internal StringBuilder to build the joined string.

    So performance-wise it's much the same as using a StringBuilder and appending to it, or using a chain of + (which nowadays are converted to StringBuilder operations by the compiler).

    But the significance of String.join is not as a general replacement for + or String.concat, but in being the "reverse operation" of a String.split operation. It makes more sense in that context - when you have a bunch of strings that you want to join together using a delimiter - than as a replacement for concat.

    That is, to build an output like "a/b/c/d" or "(a+b+c+d)" when you have a,b,c and d in an array or a list, String.join or a StringJoiner would make the operation clear and readable.

    0 讨论(0)
  • 2021-01-01 18:45

    str1 + " " + str2 is internally converted into:

    StringBuffer tmp1 = new StringBuffer();
    tmp1.append(str1);
    tmp1.append(" ");
    String tmp2 = tmp1.toString();
    StringBuffer tmp3 = new StringBuffer();
    tmp3.append(tmp2);
    tmp3.append(str2);
    String result = tmp3.toString();
    

    str1.concat(str2) will not produce the same result, as the space wont be present between the two strings.

    join should be equivalent to

    StringBuffer tmp1 = new StringBuffer();
    tmp1.append(str1);
    tmp1.append(" ");
    tmp1.append(str2);
    String result = tmp.toString();
    

    and hence be faster.

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