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

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

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

例子。
输入: Set<String> = ["Geeks", "ForGeeks", "GeeksForGeeks"]
输出: “Geeks, For, Geeks”

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

办法。这可以在String的join()方法的帮助下实现,方法如下。

  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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程