String.join () versus other string concatenation operations

I quickly read the Java8 String api documentation.

Now I'm not very curious about the String.join () method for the string concat / join.

This example helped me better understand, though:

//Old way: String str1 = "John"; String str2 = "Doe"; String result = str1 + " " +str2; //or by using str1.concat(str2); //New way: String result = String.join(" ", str1, str2); 

However, I do not understand which one I should use. Are there any differences in performance or other differences between the two processes.

Any help would be greatly appreciated.

+8
java string java-8
source share
2 answers

String.join relies on the StringJoiner class, which itself relies on an internal StringBuilder to create a concatenated string.

So this is very similar to using a StringBuilder and adding to it or using a + chain (which is currently being converted to StringBuilder operations StringBuilder compiler).

But the value of String.join not a general replacement for + or String.concat , but rather as the "reverse operation" of the String.split operation. This makes sense in this context - when you have a bunch of lines that you want to concat with a separator - instead of replacing concat .

That is, to build output like "a/b/c/d" or "(a+b+c+d)" , if the array or list contains a , b , c and d , String.join or StringJoiner will make the operation understandable and readable.

+14
source share

str1 + " " + str2 internally converted to:

 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, since space will not be present between two lines.

the connection should be equivalent

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

and therefore faster.

+1
source share

All Articles