1

I want to store a key,values pair that allows me to get the values by its position (ordering must persist) or by its key name. I was thinking to use HashMap but i do not want to iterate through all values to get the value by index.

I would need something like this:

MyCollection<String, Object> objects = new MyCollection<String, Object>();
objects.put ("id", Object1);
objects.put ("name", Object2);
// And now access the values by index:
Object obj1 = objects.get(1);
// or by key name:
Object obj2 = objects.getByKeyName("name");

What is the best collection to use (it must be android < 11 compatible>

spacebiker
  • 3,777
  • 4
  • 30
  • 49
  • 1
    Suggest you to use `LinkedHashMap` with [this solution](http://stackoverflow.com/a/13582099/1051509) – Maksim Nov 29 '13 at 11:54

1 Answers1

7

You can use LinkedHashMap. It maintains the inserted order. You cannot get by index as they all implement the Map interface. You can do this way-

public List<String> getByIndex(final LinkedHashMap<String, List<String>> myMap, final int index){
   return (List<String>)myMap.values().toArray()[index];
}
Sajal Dutta
  • 18,272
  • 11
  • 52
  • 74