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

后端 未结 14 1325
时光说笑
时光说笑 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:06

    you can use below code to get key : String [] keys = (String[]) item.keySet().toArray(new String[0]);

    and get object or list that insert in HashMap with key of this item like this : item.get(keys[position]);

    0 讨论(0)
  • 2020-12-12 19:09

    Use LinkedHashMap:

    Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries.

    0 讨论(0)
  • 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<Point, Particle> map,int index){
        return map.values().toArray(new Particle[map.values().size()])[index];
    } //68 965 ms
    
    //Syd Lambert's answer:
    public Particle getElementByIndex(LinkedHashMap<Point, Particle> 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.

    0 讨论(0)
  • 2020-12-12 19:09

    HashMap - and the underlying data structure - hash tables, do not have a notion of position. Unlike a LinkedList or Vector, the input key is transformed to a 'bucket' where the value is stored. These buckets are not ordered in a way that makes sense outside the HashMap interface and as such, the items you put into the HashMap are not in order in the sense that you would expect with the other data structures

    0 讨论(0)
  • 2020-12-12 19:09

    HashMaps don't allow access by position, it only knows about the hash code and and it can retrieve the value if it can calculate the hash code of the key. TreeMaps have a notion of ordering. Linkedhas maps preserve the order in which they entered the map.

    0 讨论(0)
  • 2020-12-12 19:11

    Use a LinkedHashMap and when you need to retrieve by position, convert the values into an ArrayList.

    LinkedHashMap<String,String> linkedHashMap = new LinkedHashMap<String,String>();
    /* Populate */
    linkedHashMap.put("key0","value0");
    linkedHashMap.put("key1","value1");
    linkedHashMap.put("key2","value2");
    /* Get by position */
    int pos = 1;
    String value = (new ArrayList<String>(linkedHashMap.values())).get(pos);
    
    0 讨论(0)
提交回复
热议问题