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

Eugene picture Eugene · Mar 8, 2011 · Viewed 181.5k times · Source

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

Answer

Kulnor picture Kulnor · Apr 28, 2011

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);