Convert Comma Separated String to HashSet in Java Example

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

How to convert comma separated string to HashSet in Java?

There are a couple of ways using which we can convert comma separated string to HashSet object in Java as given below.

1. Using the String split method and Arrays class

First, we will split the string by comma and that will return us an array. Once we get an array, we will convert it to the List using the asList method of the Arrays class. The List object than can be converted to the HashSet using the HashSet constructor.

Output

I have coded the whole process step by step for an easier explanation. However, we can also do this in a single line as given below.

Output

If the comma separated string contains spaces in addition to the commas, we need to remove them. We can do this by using the regular expression pattern “\\s*,\\s*” in the String split method. The patternĀ “\\s*,\\s*” means zero or more space followed by a comma followed by zero or more space character. Let’s try it out.

Output

As we can see from the output, all the spaces between individual values are removed now, but the first and last space characters are still there. There is a simple fix to remove them by using the String trim method.

Output

Note: As we can see from the output, the string contained “2” twice but when we converted the string to Set<String> it was added only once because Set does not allow duplicate elements.

2. Using Java 8 stream

If you are using Java version 8 or later, you can also use the stream to convert comma separated string to Set<String> object as given below.

Output

You can also use the Pattern class to convert comma separated string to Set<String> as given below.

Output

Please also visit how to convert HashSet to comma separated 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