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);}}chevron_rightfilter_noneOutput: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);}}chevron_rightfilter_noneOutput:String: Geeks For Geeks Comma separated List: [Geeks, For, Geeks]
Recommended Posts:
- Convert a List of String to a comma separated String in Java
- Convert a Set of String to a comma separated String in Java
- Program to convert List of Integer to List of String in Java
- Program to convert List of String to List of Integer in Java
- Convert a String to a List of Characters in Java
- Convert List of Characters to String in Java
- Convert an ArrayList of String to a String array in Java
- Convert List to Set in Java
- Convert an Iterator to a List in Java
- Program to Convert List to Map in Java
- Program to Convert Set to List in Java
- Convert Set of String to Array of String in Java
- Program to Convert a Vector to List in Java
- Program to Convert List to Stream in Java
- Program to convert Array to List in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



