String.join() vs other string concatenation operations

后端 未结 3 1793
时光取名叫无心
时光取名叫无心 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: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.

提交回复
热议问题