Java Convert Comma Separated String to List

Tags: StringUtils

In this Java tutorial, we learn how to implement a Java utility class to convert a comma separated String into a List of Strings in Java programming language.

How to convert comma separated String to List of Strings in Java

Firstly, create a new Java class named StringUtils. In the new class, implement a new static method named commaSeparatedStringToList(String commaSeparatedString), this method to convert an input String value in comma separated format into a List of String values as Java code below.

StringUtils.java

import java.util.Arrays;
import java.util.List;

public class StringUtils {

    /**
     * This method to convert a comma separated String into a List of Strings.
     * @param commaSeparatedString the input String.
     * @return List of String values.
     */
    public static List<String> commaSeparatedStringToList(String commaSeparatedString) {
        if(commaSeparatedString == null) {
            return null;
        }

        String[] values = commaSeparatedString.split(",");
        return Arrays.asList(values);
    }
}

In the following example Java code, we learn how to use the above utility class to convert a comma separated String into a List of Strings in Java program.

CommaSeparatedStringToListExample.java

import java.util.List;

public class CommaSeparatedStringToListExample {
    public static void main(String... args) {
        String commaSeparatedString = "Java,Spring Boot,Tutorials";

        // Convert Comma Separated String value to List object
        List<String> list = StringUtils.commaSeparatedStringToList(commaSeparatedString);

        System.out.println("Input String: " + commaSeparatedString);
        System.out.println("List of Strings: " + list);
    }
}
The output as below.
Input String: Java,Spring Boot,Tutorials
List of Strings: [Java, Spring Boot, Tutorials]

Happy Coding 😊

Java Convert Comma Separated String to Set