How to Convert Comma Separated String to HashSet in Java?
Last Updated :
17 Dec, 2020
Given a Set of String, the task is to convert the Set to a comma-separated String in Java.
Examples:
Input: Set<String> = ["Geeks", "ForGeeks", "GeeksForGeeks"]
Output: "Geeks, For, Geeks"
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
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" ;
String[] strParts = str.split( "," );
List<String> listParts = Arrays.asList(strParts);
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
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]
Share your thoughts in the comments
Please Login to comment...