Is it possible to get element from HashMap by its position?

后端 未结 14 1430
时光说笑
时光说笑 2020-12-12 18:31

How to retrieve an element from HashMap by its position, is it possible at all?

14条回答
  •  轮回少年
    2020-12-12 19:09

    Another working approach is transforming map values into an array and then retrieve element at index. Test run of 100 000 element by index searches in LinkedHashMap of 100 000 objects using following approaches led to following results:

    //My answer:
    public Particle getElementByIndex(LinkedHashMap map,int index){
        return map.values().toArray(new Particle[map.values().size()])[index];
    } //68 965 ms
    
    //Syd Lambert's answer:
    public Particle getElementByIndex(LinkedHashMap map,int index){
        return map.get( (map.keySet().toArray())[ index ] );
    } //80 700 ms
    

    All in all retrieving element by index from LinkedHashMap seems to be pretty heavy operation.

提交回复
热议问题