So, how would you go about converting
String csv = "11,00,33,66,44,33,22,00,11";
to a hashset in the quickest-most optimized way.
This is for a list of user-ids.
I ran all the answers provided through a test program where each method was called 500,000 times for a bigger CSV string. This test was performed 5 times continously (in case program startup slowed initial method) and I got the following in milliseconds (ms):
Method One Liner-> 6597 Method Split&Iterate-> 6090 Method Tokenizer-> 4306 ------------------------------------------------ Method One Liner-> 6321 Method Split&Iterate-> 6012 Method Tokenizer-> 4227 ------------------------------------------------ Method One Liner-> 6375 Method Split&Iterate-> 5986 Method Tokenizer-> 4340 ------------------------------------------------ Method One Liner-> 6283 Method Split&Iterate-> 5974 Method Tokenizer-> 4302 ------------------------------------------------ Method One Liner-> 6343 Method Split&Iterate-> 5920 Method Tokenizer-> 4227 ------------------------------------------------ static void method0_oneLiner() { for (int j = 0; j < TEST_TIMES; j++) { Set<String> hashSet = new HashSet<String>(Arrays.asList(csv .split(","))); } } // ———————————————————————————————– static void method1_splitAndIterate() { for (int j = 0; j < TEST_TIMES; j++) { String[] values = csv.split(","); HashSet<String> hSet = new HashSet<String>(values.length); for (int i = 0; i < values.length; i++) hSet.add(values[i]); } } static void method2_tokenizer() { for (int j = 0; j < TEST_TIMES; j++) { HashSet<String> hSet = new HashSet<String>(); StringTokenizer st = new StringTokenizer(csv, ","); while (st.hasMoreTokens()) hSet.add(st.nextToken()); } }
List<String> items = Arrays. asList(commaSeparated. split(",")); That should work for you.
In order to parse a comma-delimited String, you can just provide a "," as a delimiter and it will return an array of String containing individual values. The split() function internally uses Java's regular expression API (java. util. regex) to do its job.
In Java, we can use String. join(",", list) to join a List String with commas.
String[] values = csv.split(","); Set<String> hashSet = new HashSet<String>(Arrays.asList(values));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With