gpt4 book ai didi

java - 将逗号分隔的字符串转换为 HashSet

转载 作者:太空狗 更新时间:2023-10-29 22:42:41 25 4
gpt4 key购买 nike

那么,您将如何进行转换

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());
}
}

最佳答案

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

关于java - 将逗号分隔的字符串转换为 HashSet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19003055/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com