I have a comma-seperated value string in Java:
String s = "a,b,c,d";
I need to tokenize it (with comma as the delimiter) and turn it into a Set<String>. Is StringTokenizer my best bet or is there a more efficient way?
I have a comma-seperated value string in Java:
String s = "a,b,c,d";
I need to tokenize it (with comma as the delimiter) and turn it into a Set<String>. Is StringTokenizer my best bet or is there a more efficient way?
Try String.split(), that's probably the easiest.
String[] a = "a,b,c,d".split( "," );
Set<String> s = new HashSet( Arrays.asList( a ) );
Although StringTokenizer is a good option to split your input string, I personally prefer using String.split().
String[] tokens = myString.split(",");
Set<String> set = new HashSet<String>(Arrays.asList(tokens));
I would use split. split gives you an array, so
String[] toks = s.split(",")
and then
Set<String> mySet = new HashSet<String>(Arrays.asList(toks));
The Spring Framework provides StringUtils.commaDelimitedListToSet that does exactly what you're after. It's probably overkill to pull in Spring just for this, but if you're working in a framework that already includes it then it's an option to be aware of.
If you just need a simple solution without all CSV rules I would recommend StringUtils.split (instead String.split due the regex overhead):
HashSet<String> set = new HashSet<String>(Arrays.asList(StringUtils.split(text, ',')));
If you need a solution that obeys the CSV rules, you should think in use Commons CSV