String.join()vs其他字符串连接操作 [英] String.join() vs other string concatenation operations

查看:1169
本文介绍了String.join()vs其他字符串连接操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经快速阅读了Java8 String api 文档。

I have quickly read over the Java8 String api documentation.

现在我对串联/连接字符串的String.join()方法不感兴趣。

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

这种示例帮助我更好地理解:

This kind of example has helped me to understand better, 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);

但是,我不明白应该使用哪一个。这两个过程之间是否有任何表现或其他差异。

Still, I don't understand which one should I use. Is there any performance or other differences between these two processes.

任何帮助都将不胜感激。

Any help would be greatly appreciated.

推荐答案

String.join 依赖于类 StringJoiner 本身依赖内部 StringBuilder 来构建连接的字符串。

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

因此,性能方面与使用 StringBuilder 并附加到它相同,或使用 + 链(现在编译器将其转换为 StringBuilder 操作)。

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).

String.join 的重要性不是 + 或 String.concat ,但是作为 String.split 操作的反向操作。在这种情况下更有意义 - 当你有一堆字符串想要使用分隔符连接在一起时 - 而不是替换 concat

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.

即构建类似a / b / c / d的输出(a + b + c + d)当你有 a b ,<$数组或列表中的c $ c> c d String.join 或者 StringJoiner 会使操作清晰可读。

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.

这篇关于String.join()vs其他字符串连接操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆