Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get position of key/value in LinkedHashMap using its key

People also ask

How do you find the position of a key on a map?

You can't. The keys on a Map and a HashMap are not ordered. You'll need to use a structure that preserves order, such as a LinkedHashMap. Note that LinkedHashMap does not provide a method that gets keys by position, so this is only appropriate if you are going to be using an iterator.

How get values from LinkedHashMap?

You can convert all the keys of LinkedHashMap to a set using Keyset method and then convert the set to an array by using toArray method now using array index access the key and get the value from LinkedHashMap.

How do I find the key of LinkedHashMap?

In Java, get() method of LinkedHashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.

How do I sort a LinkedHashMap by key?

To sort LinkedHashMap by keys using the comparable interface in Java first, we create a class that implements the comparable interface. In this class, we override the compareTo() method. And then we pass the LinkedHashMap to TreeMap constructor to sort.


HashMap implementations in general are un-ordered for Iteration.

LinkedHashMap is predictablely ordered for Iteration ( insertion order ) but does not expose the List interface and a LinkedList ( which is what mirrors the key set insertion order ) does not track index position itself either, it is very in-efficient to find the index as well. The LinkedHashMap doesn't expose the reference to the internal LinkedList either.

The actual "Linked List" behavior is implementation specific. Some may actually use an instance of LinkedList some many just have Entry track a previous and next Entry and use that as its implementation. Don't assume anything without looking at the source.

The KeySet that contains the keys does not guarantee order as well because of the hashing algorithms used for placement in the backing data structure of the inherited HashMap. So you can't use that.

The only way to do this, without writing your own implementation, is to walk the Iterator which uses the mirroring LinkedList and keep a count where you are, this will be very in-efficient with large data sets.

Solution

What it sounds like you want is original insertion order index positions, you would have to mirror the keys in the KeySet in something like an ArrayList, keep it in sync with updates to the HashMap and use it for finding position. Creating a sub-class of HashMap, say IndexedHashMap and adding this ArrayList internally and adding a .getKeyIndex(<K> key) that delegates to the internal ArrayList .indexOf() is probably the best way to go about this.

This is what LinkedHashMap does but with a LinkedList mirroring the KeySet instead of an ArrayList.


int pos = new ArrayList<String>(info.keySet()).indexOf("jeremy")

I saw a suggestion from one of the duplicates of this question at

How get value from LinkedHashMap based on index not on key?

and I liked the suggestion as described as pseudo code from @schippi in the comments. I thought some working Java code might be useful to others on this approach

import java.util.ArrayList;
import java.util.LinkedHashMap;

public class IndexedLinkedHashMap<K,V> extends LinkedHashMap<K,V> {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    ArrayList<K> al_Index = new ArrayList<K>();

    @Override
    public V put(K key,V val) {
        if (!super.containsKey(key)) al_Index.add(key);
        V returnValue = super.put(key,val);
        return returnValue;
    }

    public V getValueAtIndex(int i){
        return (V) super.get(al_Index.get(i));
    }

    public K getKeyAtIndex(int i) {
        return (K) al_Index.get(i);
    }

    public int getIndexOf(K key) {
        return al_Index.indexOf(key);
    }

}