Java – Convert comma-separated String to List
ADVERTISEMENT
Table of Contents
Introduction
This tutorial shows several ways for converting a comma-separated String to a List in Java.
1- Java 7
With Java 7 and older versions, the typical way of converting a comma-separated String to a List is through splitting the String by the comma “,” delimiter and then generating a List using Arrays.asList() as the following:
public static List<String> convertUsingAsList(String commaSeparatedStr)
{
String[] commaSeparatedArr = commaSeparatedStr.split("\\s*,\\s*");
List<String> result = new ArrayList<String>(Arrays.asList(commaSeparatedArr));
return result;
}
2- Java 8
In Java 8, you can split the String by the comma “,” delimiter and then use Arrays.stream() and collect() methods to generate a List.
public static List<String> convertUsingJava8(String commaSeparatedStr)
{
String[] commaSeparatedArr = commaSeparatedStr.split("\\s*,\\s*");
List<String> result = Arrays.stream(commaSeparatedArr).collect(Collectors.toList());
return result;
}
Summary
This tutorial shows several ways for converting a comma-separated String to a List in Java.
Next Steps
If you're interested in learning more about the basics of Java, coding, and software development, check out our Coding Essentials Guidebook for Developers, where we cover the essential languages, concepts, and tools that you'll need to become a professional developer.
Thanks and happy coding! We hope you enjoyed this article. If you have any questions or comments, feel free to reach out to jacob@initialcommit.io.
Final Notes
Recommended product: Coding Essentials Guidebook for Developers