gpt4 book ai didi

java - 迭代以在索引处查找 Map 条目?

转载 作者:搜寻专家 更新时间:2023-10-30 21:23:41 24 4
gpt4 key购买 nike

我有一个 LinkedHashMap。我想在索引 N 处获取 Foo。除了迭代直到找到它之外,还有更好的方法吗?:

int target = N;
int index = 0;
for (Map.Entry<String, Foo> it : foos.entrySet()) {
if (index == target) {
return it.getValue();
}
index++;
}

对于某些操作,我必须通过索引从 map 中获取随机元素大约 50 次。该 map 将包含大约 20 个项目。

谢谢

最佳答案

List<Entry<String,Foo>> randAccess = new ArrayList<Entry<String,Foo>>(foos.entrySet());

然后对于具有 O(1) 访问权限的索引 N...

randAccess.get(N)

关于java - 迭代以在索引处查找 Map 条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3895525/

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