Java Convert Comma Separated String to Set

Tags: StringUtils

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

How to convert a comma separated String to Set in Java

At the first step, create a new Java class named StringUtils, and implement a new static method named commaSeparatedStringToSet(String commaSeparatedString), in method we follow these steps to convert a String into Set.

  • Step 1: split the String into an array of String values.
  • Step 2: create a List object from an array of Strings.
  • Step 3: Create a new HashSet object from List object.

StringUtils.java

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class StringUtils {

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

        String[] values = commaSeparatedString.split(",");
        List<String> list = Arrays.asList(values);
        Set<String> result = new HashSet<>(list);
        return result;
    }
}

In the following example Java code, we learn how to use the above StringUtils.commaSeparatedStringToSet() method to convert a comma separated String into Set object in Java program.

CommaSeparatedStringToSetExample.java

import java.util.Set;

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

        // Convert Comma Separated String value to Set object
        Set<String> set = StringUtils.commaSeparatedStringToSet(commaSeparatedString);

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

Happy Coding 😊

Java Convert Comma Separated String to List