📌  相关文章
📜  在Java中将String转换为逗号分隔的List

📅  最后修改于: 2022-05-13 01:54:25.137000             🧑  作者: Mango

在Java中将String转换为逗号分隔的List

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

例子:

Input: String = "Geeks For Geeks"
Output: List = [Geeks, For, Geeks]

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

方法:这可以通过将字符串转换为字符串数组,然后从该数组创建一个列表来实现。但是,此列表可以根据其创建方法分为 2 种类型 - 可修改和不可修改。

  • 创建一个不可修改的列表
    // 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 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
                list = new ArrayList(
                    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]