How to Convert Comma Separated String to HashSet in Java?

To convert a comma-separated string to a HashSet in Java, you can follow these steps:

  1. Split the comma-separated string into an array of strings using the split() method of the String class.
  2. Create a new HashSet object to store the elements.
  3. Add the elements from the array to the HashSet using the add() method of the HashSet class.

Here's an example code snippet that demonstrates this process: 

 

String csv = "apple,banana,orange";
String[] items = csv.split(",");
Set set = new HashSet<>();
for (String item : items) {
    set.add(item);
}

In this example, the csv variable contains the comma-separated string, which is split into an array of strings using the split() method. Then, a new HashSet is created to store the elements, and each element from the array is added to the HashSet using the add() method.

Note that if the comma-separated string contains whitespace between the commas and the elements, you may want to trim the elements using the trim() method to remove any leading or trailing whitespace: 

 

String csv = "apple, banana,  orange ";
String[] items = csv.split(",");
Set set = new HashSet<>();
for (String item : items) {
    set.add(item.trim());
}

Here, the trim() method is called on each element to remove any leading or trailing whitespace before adding it to the HashSet.

Submit Your Programming Assignment Details