Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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";
SetString> 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 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";
SetString> 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(",");
ListString> list = Arrays.asList(strArr);
HashSetString> 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.


This post first appeared on Java Hungry, please read the originial post: here

Share the post

Convert Comma-Separated String to HashSet in Java

×

Subscribe to Java Hungry

Get updates delivered right to your inbox!

Thank you for your subscription

×