How to Convert Comma Separated String to HashSet in Java?
Given a Set of String, the task is to convert the Set to a comma-separated String in Java.
Examples:
Input: Set<String> = ["Beginner", "ForBeginner", "w3wiki"] Output: "Beginner, For, Beginner" Input: Set<String> = ["G", "e", "e", "k", "s"] Output: "G, e, e, k, s"
There are two ways in which we can convert comma separated string to Java HashSet :
Method 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 then can be converted to the HashSet using the HashSet constructor.
Java
// Java program to convert comma // separated string to HashSet import java.util.Arrays; import java.util.HashSet; import java.util.List; public class StringToHashSetExample { public static void main(String[] args) { String str = "1,2,3,4,2,5" ; // split the string by comma String[] strParts = str.split( "," ); // convert array to the List using asList method List<String> listParts = Arrays.asList(strParts); // create HashSet from the List using constructor HashSet<String> hsetFromString = new HashSet<String>( listParts ); System.out.println( "HashSet contains: " + hsetFromString); } } |
Output
HashSet contains: [1, 2, 3, 4, 5]
Method 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.
Java
// Java program to convert comma // separated string to HashSet import java.util.*; import java.io.*; import java.util.stream.*; public class StringToHashSetExample { public static void main(String[] args) { String str = "1,2,3,4,2,5" ; Set<String> set = Stream.of(str.trim().split( "\\s*,\\s*" )) .collect(Collectors.toSet()); System.out.println( "HashSet contains: " + set); } } |
Output
HashSet contains: [1, 2, 3, 4, 5]