Fastest way to put contents of Setlt;Stringgt; to a single String with words separated by a whitespace?(放置 Setlt;Stringgt; 内容的最快方法到单个字符串,单词由空格分隔?)
问题描述
我有几个 Set<String>
并希望将它们中的每一个转换为单个 String
,其中原始 Set
由空格"分隔.一个天真的第一种方法是这样做
I have a few Set<String>
s and want to transform each of these into a single String
where each element of the original Set
is separated by a whitespace " ".
A naive first approach is doing it like this
Set<String> set_1;
Set<String> set_2;
StringBuilder builder = new StringBuilder();
for (String str : set_1) {
builder.append(str).append(" ");
}
this.string_1 = builder.toString();
builder = new StringBuilder();
for (String str : set_2) {
builder.append(str).append(" ");
}
this.string_2 = builder.toString();
谁能想到一种更快、更漂亮或更有效的方法来做到这一点?
Can anyone think of a faster, prettier or more efficient way to do this?
推荐答案
使用 commons/lang 你可以使用 StringUtils.join:
String str_1 = StringUtils.join(set_1, " ");
为了简洁,你无法真正击败它.
You can't really beat that for brevity.
更新:
重新阅读这个答案,我现在更喜欢关于番石榴木匠的其他答案.事实上,这些天我并没有靠近 apache commons.
Re-reading this answer, I would prefer the other answer regarding Guava's Joiner now. In fact, these days I don't go near apache commons.
另一个更新:
Java 8 引入了方法 String.join()
Java 8 introduced the method String.join()
String joined = String.join(",", set);
虽然这不如 Guava 版本灵活,但当您的类路径中没有 Guava 库时,它会很方便.
While this isn't as flexible as the Guava version, it's handy when you don't have the Guava library on your classpath.
这篇关于放置 Set<String> 内容的最快方法到单个字符串,单词由空格分隔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:放置 Set<String> 内容的最快方法到单个字符串,单词由空格分隔?
基础教程推荐
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 降序排序:Java Map 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01