问题描述
我有几个 set
i have a few set
setset_1; set 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.