Iterate to find a Map entry at an index?

前端 未结 4 1825
小鲜肉
小鲜肉 2020-12-20 13:35

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 =         


        
相关标签:
4条回答
  • 2020-12-20 13:50

    Guava library can help in this case:

    public static <T> T com.google.common.collect.Iterables.get(Iterable<T> iterable, int position)
    

    see javadoc: Iterables.get

    For your case the code can be like this:

    Iterables.get(foos.values(), N);
    
    0 讨论(0)
  • 2020-12-20 13:51

    @Mark's solution is spot on. I'd just like to point out that the offsets (positions) of the entries in a map (of any kind) are not stable. Each time an entry is added or removed, the offsets of the remaining entries may change. For a HashMap or LinkedHashMap, you've no way of knowing which entry's offsets will change.

    • For a regular HashMap, a single insertion can apparently "randomize" the entry offsets.
    • For a LinkedHashMap, the order of the entries is stable, the actual entry offsets are not.

    The instability of the offsets and the fact that finding entry at a given offset is expensive for all standard map implementations are the reasons why the Map interface does not provide a get(int offset) method. It should also be a hint that it is not a good idea for an algorithm to need to do this sort of thing.

    0 讨论(0)
  • 2020-12-20 13:53
    List<Entry<String,Foo>> randAccess = new ArrayList<Entry<String,Foo>>(foos.entrySet());
    

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

    randAccess.get(N)
    
    0 讨论(0)
  • 2020-12-20 14:09

    A simplification of @Mark's solution... You only need the values, so each time you change a value in the foos Map, also update an array.

    Map<String, Foo> foos =;
    Foo[] fooValues = {};
    
    foos.put(foos.name(), foo);
    fooValues = foos.values().toArray(new Foo[foos.size()]);
    
    // later
    Foo foo = fooValues[N];
    
    0 讨论(0)
提交回复
热议问题