user291701 user291701 - 1 year ago 71
Java Question

Iterate to find a Map entry at an index?

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

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.


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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download