Convert Comma-Separated String to HashSet in Java

In this post, I will be sharing how to convert comma-separated String to HashSet in Java. There are three  ways to achieve our goal:
1. Using Java8 Stream
2. Using Pattern class
3. Using String's split() and Arrays asList() method

Read Also: Convert HashSet to String in Java

Convert Comma-Separated String to HashSet in Java

1. Using Java8 Stream


We can convert comma-separated String to HashSet using Collectors.toSet() method as shown below in the example:

import java.util.HashSet;
import java.util.Set;
import java.util.stream.*;

public class StringToHashSetOne {    
  public static void main(String[] args) {
    String givenString = "Be, in, Present";
    Set<String> result = Stream.of(givenString.trim().split(",")).collect(Collectors.toSet());
    System.out.println(result);
    
  }
}

Output:
[Be, in, Present]

2. Using Pattern class


Using Pattern class also we can convert comma-separated String to the HashSet<String> as shown in the example below:

import java.util.stream.*;
import java.util.regex.Pattern;
import java.util.Set;

public class StringToHashSetTwo {    
  public static void main(String[] args) {
    String givenString = "Alive, is, Awesome";
    Set<String> result = Pattern.compile("\\s*,\\s*").splitAsStream(givenString.trim()).collect(Collectors.toSet());
    System.out.println(result);
  }
}


Output:
[Awesome, is, Alive]

3. Using split() and Arrays.asList() method


Using String class split() method and Arrays.asList() method we can convert comma-separated string to the HashSet. Please refer below example:

import java.util.Set;
import java.util.HashSet;
import java.util.List;
import java.util.Arrays;

public class StringToHashSetThree {    
  public static void main(String[] args) {
    String givenString = "Boston, NewYork, Chicago";
    String[] strArr = givenString.split(",");
    List<String> list = Arrays.asList(strArr);
    HashSet<String>  set = new HashSet<>(list);
    System.out.println(set);
  }
}


Output:
[ NewYork, Boston, Chicago]

That's all for today. Please mention in the comments in case you have any questions related to convert comma-separated String to HashSet in Java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry