将字符串转换为逗号分隔的列表(Java实现)

将字符串转换为逗号分隔的列表(Java实现)

给定一个字符串,将其转换为逗号分隔的列表。

例如:

输入:String = "Geeks For Geeks"
输出:List = [Geeks, For, Geeks]
输入:String = "G e e k s"
输出:List = [G, e, e, k, s]

在进行此解决方案之前,建议先在 {IDE} 上尝试自己的方法。

解决方法:可以通过将字符串转换为字符串数组,然后从该数组创建列表来实现。但是,这个列表可以根据它们的创建方法分为两种类型——可修改的列表和不可修改的列表。

  • 创建一个不可修改的列表:
// Java program to convert String
// to comma separated List
  
import java.util.*;
  
public class GFG {
    public static void main(String args[])
    {
  
        // Get the String
        String string = "Geeks For Geeks";
  
        // Print the String
        System.out.println("String: " + string);
  
        // convert String to array of String
        String[] elements = string.split(" ");
  
        // Convert String array to List of String
        // This List is unmodifiable
        List<String> list = Arrays.asList(elements);
  
        // Print the comma separated List
        System.out.println("Comma separated List: "
                           + list);
    }
}

输出:

String: Geeks For Geeks
Comma separated List: [Geeks, For, Geeks]
  • 创建一个可修改的列表:
// Java program to convert String
// to comma separated List
  
import java.util.*;
  
public class GFG {
    public static void main(String args[])
    {
  
        // Get the String
        String string = "Geeks For Geeks";
  
        // Print the String
        System.out.println("String: " + string);
  
        // convert String to array of String
        String[] elements = string.split(" ");
  
        // Convert String array to List of String
        // This List is modifiable
        List<String>
            list = new ArrayList<String>(
                Arrays.asList(elements));
  
        // Print the comma separated List
        System.out.println("Comma separated List: "
                           + list);
    }
}

输出:

String: Geeks For Geeks
Comma separated List: [Geeks, For, Geeks]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程