Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

hashmap

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

like image 668
Eugene Avatar asked Mar 08 '11 19:03

Eugene


People also ask

Can you access a HashMap by index?

HashMap stores items as key/value pairs. Values can be accessed by indexes, known as keys, of a user-defined type.

How do you access the elements of a HashMap?

To access elements in a HashMap in a loop, we use the foreach (enhanced for) loop and the . keySet() or . values() methods. The keySet method will retrieve the keys in the HashMap.

How do you get a specific value from a Map?

HashMap. get() method of HashMap 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.


1 Answers

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); 
like image 77
Kulnor Avatar answered Sep 21 '22 00:09

Kulnor