Fastest way to put contents of Set to a single String with words separated by a whitespace?

后端 未结 8 1589
不思量自难忘°
不思量自难忘° 2020-12-05 03:34

I have a few Sets and want to transform each of these into a single String where each element of the original Set is sep

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 04:35

    With commons/lang you can do this using StringUtils.join:

    String str_1 = StringUtils.join(set_1, " ");
    

    You can't really beat that for brevity.

    Update:

    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.

    Another Update:

    Java 8 introduced the method String.join()

    String joined = String.join(",", set);
    

    While this isn't as flexible as the Guava version, it's handy when you don't have the Guava library on your classpath.

提交回复
热议问题