1. Using Java 8 Stream API
2. Using String's split() and Arrays asList() method
3. Using Pattern class
Read Also: Convert ArrayList to String Array in Java
Let's dive deep into the topic:
Convert Comma-Separated String to List in Java
1. Using Java 8 Stream API
We can convert comma-separated String to List using the Collectors.toList() method as shown below in the example:
import java.util.List; import java.util.stream.*; public class StringToListOne { public static void main(String args[]) { String givenString = "Alive, is, Awesome"; List<String> result = Stream.of(givenString.trim().split(",")).collect(Collectors.toList()); System.out.println(result); } }
Output:
[Alive, is, Awesome]
2. Using String's split() and Arrays asList() method
Using the String class split() method and Arrays.asList() method we can convert comma-separated string to the List as shown in the below example.
import java.util.List; import java.util.Arrays; public class StringToListTwo { public static void main(String args[]) { String givenString = "Be, in, Present"; String[] arr = givenString.split(","); List<String> list = Arrays.asList(arr); System.out.println(list); } }
Output:
[Be, in, Present]
3. Using Pattern class
Using Pattern class also we can convert comma-separated String to the List<String> as shown in the example below:
import java.util.List; import java.util.stream.*; import java.util.regex.Pattern; public class StringToListThree { public static void main(String args[]) { String givenString = "Love, Yourself"; List<String> result = Pattern.compile("\\s*,\\s*").splitAsStream(givenString.trim()).collect(Collectors.toList()); System.out.println(result); } }
Output:
[Love, Yourself]
That's all for today. Please mention in the comments in case you have any questions related to how to convert comma-separated String to List in Java.