Skip to content
Related Articles

Related Articles

How to Convert Comma Separated String to HashSet in Java?
  • Last Updated : 17 Dec, 2020
GeeksforGeeks - Summer Carnival Banner

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




// 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]

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :