Convert comma separated string into a HashSet

The 6 other answers are great, in that they're the most straight-forward way of converting.

However, since String.split() involves regexps, and Arrays.asList is doing redundant conversion, you might want to do it this way, which may improve performance somewhat.

Edit if you have a general idea on how many items you will have, use the HashSet constructor parameter to avoid unnecessary resizing/hashing :

HashSet<String> myHashSet = new HashSet(500000);  // Or a more realistic size
StringTokenizer st = new StringTokenizer(csv, ",");
while(st.hasMoreTokens())
   myHashSet.add(st.nextToken());

String[] values = csv.split(",");
Set<String> hashSet = new HashSet<String>(Arrays.asList(values));

Arrays.stream(csv.split(",")).collect(Collectors.toSet());

Tags:

Java

Csv

Hashset