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:
import java.util.*;
public class GFG {
public static void main(String args[])
{
String string = "Geeks For Geeks" ;
System.out.println( "String: " + string);
String[] elements = string.split( " " );
List<String> list = Arrays.asList(elements);
System.out.println( "Comma separated List: "
+ list);
}
}
|
Output:
String: Geeks For Geeks
Comma separated List: [Geeks, For, Geeks]
- Creating a modifiable List:
import java.util.*;
public class GFG {
public static void main(String args[])
{
String string = "Geeks For Geeks" ;
System.out.println( "String: " + string);
String[] elements = string.split( " " );
List<String>
list = new ArrayList<String>(
Arrays.asList(elements));
System.out.println( "Comma separated List: "
+ list);
}
}
|
Output:
String: Geeks For Geeks
Comma separated List: [Geeks, For, Geeks]
Last Updated :
11 Dec, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...