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

后端 未结 8 1587
不思量自难忘°
不思量自难忘° 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条回答
  •  猫巷女王i
    2020-12-05 04:28

    If you are using Java 8, you can use the native

    String.join(CharSequence delimiter, Iterable elements)
    

    method:

    Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter. For example:

     Set strings = new LinkedHashSet<>();
     strings.add("Java"); strings.add("is");
     strings.add("very"); strings.add("cool");
     String message = String.join("-", strings);
     //message returned is: "Java-is-very-cool"
    

    Set implements Iterable, so simply use:

    String.join(" ", set_1);
    

提交回复
热议问题