How get value from LinkedHashMap based on index not on key? [duplicate]

I have

LinkedHashMap<String, List<String>> hMap;

I want to get List<String> by position not on key.

I don't want to use iterate.

Is there any other way to get Value based on index ?


Solution 1:

You can't get the value of the Map based on index, Maps just don't work that way. A workaround would be to create a new list from your values and get the value based on index.

LinkedHashMap<String, List<String>> hMap;
List<List<String>> l = new ArrayList<List<String>>(hMap.values());
l.get(0);

Solution 2:

public List<String> getByIndex(LinkedHashMap<String, List<String>> hMap, int index){
   return (List<String>) hMap.values().toArray()[index];
}

Solution 3:

you may want to consider either using another class to store your data, or write an extension to the linkedHashMap. something like

//this is pseudo code
public class IndexedLinkedHashMap<K,V> extends LinkedHashMap{

HashMap<int,K> index;
int curr = 0;

    @Override
    public void add(K key,V val){
        super.add(key,val);
        index.add(curr++, key);
    }

    public V getindexed(int i){
        return super.get(index.get(i));
    }

}