Is there a way of iterating a LinkedHashMap
(which has a defined order) by using an index instead of a foreach
loop? I need to access elements using index.
The following code prints the entire map:
public void print(Map<String, Integer> map)
{
for (Map.Entry<String, Integer> entryMap : map.entrySet())
{
System.out.println(entryMap.getValue() + " = " + entryMap.getKey());
}
}
How can I do the same but access the elements using index instead?
public void print(Map<String, Integer> map)
{
for (int i = 0; i< map.size(); i++)
{
// getValue() and getKey() are undefined
System.out.println(map.get(i).getValue() + " = " + map.get(i).getKey());
}
}
The following only returns the keys, but I also need the values:
public String getByIndex(Map<String, Integer> map, int index)
{
List<String> keys = new ArrayList<>(map.keySet());
return (String) keys.get(index);
}