Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert comma separated string into a HashSet

Tags:

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.

Update

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());         }     } 
like image 856
Menelaos Avatar asked Sep 25 '13 10:09

Menelaos


People also ask

How do you add a comma separated string to an ArrayList in Java?

List<String> items = Arrays. asList(commaSeparated. split(",")); That should work for you.

How do you read a comma separated string in Java?

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.

How do you concatenate a string with a comma in Java?

In Java, we can use String. join(",", list) to join a List String with commas.


1 Answers

String[] values = csv.split(","); Set<String> hashSet = new HashSet<String>(Arrays.asList(values)); 
like image 199
TheKojuEffect Avatar answered Oct 28 '22 17:10

TheKojuEffect