Convert String into comma separated List in Java

Given a String, the task is to convert it into comma separated List.
Examples:
Input: String = "Geeks For Geeks" Output: List = [Geeks, For, Geeks] Input: String = "G e e k s" Output: List = [G, e, e, k, s]
Approach: This can be achieved by converting the String into String Array, and then creating an List from that array. However this List can be of 2 types based on their method of creation – modifiable, and unmodifiable.
- Creating an unmodifiable List:
// Java program to convert String// to comma separated Listimportjava.util.*;publicclassGFG {publicstaticvoidmain(String args[]){// Get the StringString string ="Geeks For Geeks";// Print the StringSystem.out.println("String: "+ string);// convert String to array of StringString[] elements = string.split(" ");// Convert String array to List of String// This List is unmodifiableList<String> list = Arrays.asList(elements);// Print the comma separated ListSystem.out.println("Comma separated List: "+ list);}}Output:String: Geeks For Geeks Comma separated List: [Geeks, For, Geeks]
- Creating a modifiable List:
// Java program to convert String// to comma separated Listimportjava.util.*;publicclassGFG {publicstaticvoidmain(String args[]){// Get the StringString string ="Geeks For Geeks";// Print the StringSystem.out.println("String: "+ string);// convert String to array of StringString[] elements = string.split(" ");// Convert String array to List of String// This List is modifiableList<String>list =newArrayList<String>(Arrays.asList(elements));// Print the comma separated ListSystem.out.println("Comma separated List: "+ list);}}Output:String: Geeks For Geeks Comma separated List: [Geeks, For, Geeks]



