How to convert comma-separated String to List?
To convert a comma-separated
String to a
List in Java, you can use the
String.split() method to split the string into an array of substrings, and then use the
Arrays.asList() method to create a list from that array.
For example, given the following string:
String s = "apple,banana,cherry";
You can use the following code to convert it to a
String array = s.split(","); List<String> list = Arrays.asList(array);
This will create a
List containing the following elements: "apple", "banana", "cherry".
Keep in mind that the
Arrays.asList() method returns a fixed-size list, which is backed by the original array. This means that any changes you make to the list will be reflected in the array, and vice versa. If you need a modifiable list, you can use the ArrayList class instead:
String array = s.split(","); List<String> list = new ArrayList<>(Arrays.asList(array));