那么,您将如何进行转换
String csv = "11,00,33,66,44,33,22,00,11";
以最快最优化的方式到一个哈希集。
这是一个用户 ID 列表。
更新
我运行了通过测试程序提供的所有答案,其中每个方法被调用 500,000 次以获得更大的 CSV 字符串。该测试连续执行 5 次(以防程序启动减慢初始方法),我得到以下以毫秒 (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());
}
}