迭代在索引处找到Map条目? [英] Iterate to find a Map entry at an index?

查看:164
本文介绍了迭代在索引处找到Map条目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a LinkedHashMap. I want to get the Foo at index N. Is there a better way of doing this besides iterating until I find it?:

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

我必须通过索引从地图中获取大约50次的随机元素一些操作。地图中将包含大约20个项目。

I have to do get random elements from the map by an index about 50 times for some operation. The map will have about 20 items in it.

谢谢

推荐答案

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

然后索引N,O(1)访问...

Then for index N with O(1) access...

randAccess.get(N)

这篇关于迭代在索引处找到Map条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆