Java 字符串集合转逗号分隔字符串:完整示例与实现


发布日期 : 2020-12-07 03:35:07 UTC

访问量: 10 次浏览

Java 把一个字符串集转换为逗号分隔的字符串

给定一个字符串集,任务是在Java中把该字符串集转换为逗号分隔的字符串。

例子

输入:
Set<String> = ["Geeks", "ForGeeks", "GeeksForGeeks"]

输出: “Geeks, For, Geeks”

输入:
Set<String> = ["G", "e", "e", "k", "s"]

输出: “G, e, e, k, s”

方法

这可以在 Stringjoin() 方法的帮助下实现,步骤如下。

  1. 获取字符串集。
  2. 使用 join() 方法将逗号 ", " 和字符串集作为参数,从字符串集中形成一个逗号分隔的字符串。
  3. 打印该字符串。

下面是上述方法的实现。

// Java program to convert Set of String
// to comma separated String
  
import java.util.*;
  
public class GFG {
    public static void main(String args[])
    {
  
        // Get the Set of String
        Set<String>
            set = new HashSet<>(
                Arrays
                    .asList("Geeks",
                            "ForGeeks",
                            "GeeksForGeeks"));
  
        // Print the Set of String
        System.out.println("Set of String: " + set);
  
        // Convert the Set of String to String
        String string = String.join(", ", set);
  
        // Print the comma separated String
        System.out.println("Comma separated String: "
                           + string);
    }
}

输出:

Set of String: [ForGeeks, Geeks, GeeksForGeeks]
Comma separated String: ForGeeks, Geeks, GeeksForGeeks