放置Set< String>内容的最快方法到单个字符串,单词之间用空格隔开? [英] Fastest way to put contents of Set<String> to a single String with words separated by a whitespace?

查看:83
本文介绍了放置Set< String>内容的最快方法到单个字符串,单词之间用空格隔开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个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,您可以使用

为了简洁起见,你真的不能击败它.

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引入了方法

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&lt; String&gt;内容的最快方法到单个字符串,单词之间用空格隔开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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