To convert a comma-separated String to List in Java, we can use the split() method of String class that returns an array of String further, we can use this array to get a list of elements. In this article, we will use split(), asList(), toList(), etc methods. Let's see the examples.
Latest Solution: Java 8+ version
If you are working with Java 8 or a higher version then use this code. The split() method returns an array of String, we trim all the whitespace by using the String::trim and then Collectors.toList() method returns a list of String elements. See the code examples.
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/*
* Code example of convert comma-separated String to list in Java
*/
public class JExercise {
public static void main(String[] args){
// Take a String
String str = "Hello, Javaexercise";
System.out.println(str);
List<String> list= Stream.of(str.split(","))
.map(String::trim)
.collect(Collectors.toList());
System.out.println(list);
}
}
Output:
Hello, Javaexercise
[Hello, Javaexercise]
You can use this classic solution where a string is converted to an array by using the split() method and then the array is converted into a list by using the asList() method of the Arrays class. See the simplified code.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/*
* Code example of convert comma-separated String to list in Java
*/
public class JExercise {
public static void main(String[] args){
// Take a String
String str = "Hello, Javaexercise";
System.out.println(str);
List<String> list= new ArrayList<>(Arrays.asList(str.split(",")));
System.out.println(list);
}
}
Output:
Hello, Javaexercise
[Hello, Javaexercise]
We have learned to convert comma-separated string to list by using the Java stream API, split() method, and toList() method of Collectors class. Hope you get the solution. Happy Coding!