How to retrieve an element from HashMap by its position, is it possible at all?
HashMap stores items as key/value pairs. Values can be accessed by indexes, known as keys, of a user-defined type.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With