有没有通过使用索引而不是foreach
循环来迭代LinkedHashMap
(其具有定义的顺序)的方法?我需要使用索引访问元素。使用索引获取映射值对
下面的代码打印整个地图:
public void print(Map<String, Integer> map)
{
for (Map.Entry<String, Integer> entryMap : map.entrySet())
{
System.out.println(entryMap.getValue() + " = " + entryMap.getKey());
}
}
我怎么可以这样做,但使用索引而不是访问的元素?
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());
}
}
只有下面的返回键,但我还需要值:
public String getByIndex(Map<String, Integer> map, int index)
{
List<String> keys = new ArrayList<>(map.keySet());
return (String) keys.get(index);
}
重复副本在http://stackoverflow.com/questions/13581997/how-get-value-from-linkedhashmap-based-on-index-not-on-key – 2014-11-05 20:01:13
'LinkedHashMap'保留了插入顺序,因此使用增强for循环迭代其值'()'应该以相同的顺序为您提供元素。如果你需要一个计数器,只需在for循环里面定义它就可以了。 – A4L 2014-11-05 20:02:00
在处理条目时你是否只需要索引,还是需要随机访问?如果是前者,你可以创建一个Pair类和一串'Pair>'值,然后你不需要建立一个完整的并行副本。如果是后者,迭代'entrySet()'并将值放入'ArrayList >'。 –
2014-11-05 20:10:22