Java 把字符串列表转换为逗号分隔的字符串

Java 把字符串列表转换为逗号分隔的字符串

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

例子

Input: List<String> = ["Geeks", "ForGeeks", "GeeksForGeeks"]
Output: "Geeks, For, Geeks"

Input: List<String> = ["G", "e", "e", "k", "s"]
Output: "G, e, e, k, s"

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

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

下面是上述方法的实现。

程序

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

输出

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程