迭代在索引处找到Map条目?

use*_*701 11 java

我有一个LinkedHashMap.我想在索引N处得到Foo.除了迭代之外,有没有更好的方法来做到这一点直到找到它?

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

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

谢谢

Mar*_*iot 14

List<Entry<String,Foo>> randAccess = new ArrayList<Entry<String,Foo>>(foos.entrySet());
Run Code Online (Sandbox Code Playgroud)

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

randAccess.get(N)
Run Code Online (Sandbox Code Playgroud)

  • 您花了O(N)在地图中创建所有键的副本.如果有任何内容插入到地图中,则不会更新您的副本.*初始拷贝*之后的连续查询只有O(1). (5认同)