Java HashSet to Comma Separated String Example

This example shows how to convert HashSet to a comma separated string in Java. This example also shows how to convert Set<String> to String using various methods.

How to convert HashSet to comma separated String in Java?

There are several ways using which we can convert Set<String> to comma separated string in Java.

1. Using the join method of the String class (Java 8 and later versions)

The join method of the String class can be used for this conversion.

The join method returns a new String object made from the specified elements joined by the specified delimiter. This method is only available from Java version 8. If you are using an older version of Java, the join method is not available and you need to use other approaches given in this example.

Output

2. Using Apache Commons

If you are using the Apache Commons library, you can use the join method of the StringUtils class.

Output

3. Using the toString method

The toString method of the HashSet class returns a string representation of all the elements of the HashSet in “[element 1, element 2,….element n]” format.

Output

If you want to remove the enclosing square brackets and spaces, you can remove them by using below given regular expression along with the String replaceAll method.

Output

4. Using the Iterator and StringBuilder

This approach does not use any built-in methods to convert Set<String> to a comma-separated string. Instead, it uses the Iterator to iterate through HashSet elements and append them to the StringBuilder object one by one.

Output

Note: The StringBuilder class was introduced in Java version 1.5. If you are using Java 1.4 or older version, you can use the StringBuffer class instead.

In addition to these approaches, if you are using Google’s Guava library in your project, you can also use the Joiner class to convert HashSet to comma separated string.

Please also visit how to convert comma separated string to HashSet or Set<String> example to know more.

This example is a part of the Java HashSet Tutorial with Examples.

Please let me know your views in the comments section below.

References:
Java 8 HashSet

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *

Online Shopping