Java – Convert comma-separated String to List
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:
1 2 3 4 5 6 | 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.
1 2 3 4 5 6 | public static List<String> convertUsingJava8(String commaSeparatedStr) { String[] commaSeparatedArr = commaSeparatedStr.split("\\s*,\\s*"); List<String> result = Arrays.stream(commaSeparatedArr).collect(Collectors.toList()); return result; } |
java8 , Arrays.asList(commalist.split(“,”));