Read Also: How to Shuffle a String in Java
Convert HashSet to String in Java
1. Using Java8 String.join() method
String class join() method takes a delimiter and elements as shown below in the example.
import java.util.Set; import java.util.HashSet; public class HashSetToString { public static void main(String[] args) { HashSet<String> set = new HashSet(); set.add("Boston"); set.add("NewYork"); set.add("SanFrancisco"); set.add("Washington"); String result = String.join("", set); System.out.println(result); } }
Output:
SanFranciscoNewYorkWashingtonBoston
If you want a comma-separated String then replace the delimiter "" with "," in the above code.
String result = String.join(",", set);
Output:
SanFrancisco,NewYork,Washington,Boston
2. Using toString() method
We can also convert HashSet to String using the toString() method as shown below in the example.
import java.util.HashSet; public class HashSetToStringTwo { public static void main(String[] args) { HashSet<String> set = new HashSet(); set.add("Apple"); set.add("Google"); set.add("Facebook"); set.add("Amazon"); String result = set.toString(); System.out.println(result); } }
Output:
[Google, Apple, Amazon, Facebook]
You will notice that the above Output contains enclosing square brackets, commas, and spaces. If you want to get rid of brackets, commas, and spaces then you need to use regex as shown below in the example:
String result = set.toString().replaceAll("\\,|\\[|\\]|\\s", "");
Output:
GoogleAppleAmazonFacebook
3. Using Apache Commons
We can convert HashSet to String in Java using Apache Common's StringUtils class join() method as shown below in the example.
import java.util.HashSet; public class HashSetToStringThree { public static void main(String[] args) { HashSet<String> set = new HashSet(); set.add("Alive"); set.add("is"); set.add("Awesome"); String result = StringUtils.join(set, ","); System.out.println(result); } }
Output:
Awesome,is,Alive
That's all for today, please mention in comments in case you have any other questions related to convert HashSet to String in Java.