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

后端 未结 8 1562
不思量自难忘°
不思量自难忘° 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:29

    This can be done by creating a stream out of the set and then combine the elements using a reduce operation as shown below (for more details about Java 8 streams check here):

    Optional<String> joinedString = set1.stream().reduce(new 
    BinaryOperator<String>() {
    
         @Override
         public String apply(String t, String u) {
    
           return t + " " + u;
        }
    });
    return joinedString.orElse("");
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题