使用索引获取映射值对
有没有通过使用索引而不是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);
}
那么你可以写这样做的方法。
public static <K, V> Map.Entry<K, V> getEntryByIndex(Map<K, V> map, int i) {
if(i >= map.size()) {
throw new IndexOutOfBoundsException(String.valueOf(i));
}
// use Iterator
Iterator<Map.Entry<K, V>> it = map.entrySet().iterator();
// skip to i
for(; i > 0; --i) {
it.next();
}
return it.next();
}
这几乎把它当作一个链表。如果你发现你做了很多,你可能想永久保留一个ArrayList和Map。
一个可能的解决方法将是把所有的钥匙也到ArrayList中,他们可以使用索引来访问。直接访问似乎不可能,因为keySet返回一个不支持索引访问的集合。
我曾尝试过,但它只从地图返回'keys',但我也需要'values'。 – BullyWiiPlaza 2014-11-05 20:02:06
将键,而不是值放入ArrayList。您可以根据需要直接从地图中使用密钥获取该值。 – h22 2014-11-05 20:02:57
试试这个:
List<String> keys = new ArrayList(map.keySet());
for (int i = 0; i < keys.size(); i++)
{
String key = keys.get(i);
Integer value = map.get(key);
//...
}
重复副本在http://*.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