In this guide, we will discuss, how to convert a comma separated string to HashSet in Java. We will be using the String split() method to split the string into multiple substrings and then these substrings will be stored as HashSet elements.
Input String: "text1,text2,text3"
Output HashSet Elements: ["text1", "text2", "text3"]
Input String: "Apple,Orange,Banana"
Output HashSet Elements: ["Apple", "Orange", "Banana"]
Example 1: Using String split() method and Arrays
In this example, we will split the given comma separated string to HashSet using String.split() method. The Steps are as follows:
- Split the given comma separated to substrings using split() method.
- Store the returned string elements in a String array.
- Pass this array to a List by using Arrays.asList() method which converts string array to a List.
- Convert the List obtained in previous step to HashSet by passing it in the HashSet constructor.
import java.util.Arrays; import java.util.HashSet; import java.util.List; public class JavaExample { public static void main(String[] args) { String str = "text1,text2,text3"; // split the string by comma - and store the substrings // in the string array subStr String[] subStr = str.split(","); // convert string array to the List using asList() method List<String> strList = Arrays.asList(subStr); // Pass the list obtained in the previous step to HashSet // constructor to get an equivalent Set HashSet<String> hSet = new HashSet<>(strList); System.out.println("Input string: "+str); System.out.println("HashSet Elements: " + hSet); } }
Output:
Example 2: Using Java 8 Stream API
Java 8 introduced a new concept of streams. You can use Java 8 stream to convert the given comma separated string to HashSet.
import java.util.*; import java.util.stream.*; public class JavaExample { public static void main(String[] args) { String str = "AA,BB,CC,DD,EE"; //Using Java 8 Stream to convert the string to HashSet //Pass the delimiter between double quotes, // here we have comma as a delimiter Set<String> hSet = Stream.of(str.trim().split(",")) .collect(Collectors.toSet()); System.out.println("HashSet Elements: " + hSet); } }
Output:
HashSet Elements: [AA, BB, CC, DD, EE]