我有一个简单的问题。
我设置:
HashMap<A, B> myMap = new HashMap<A, B>();
...
myMap.put(...)
...
现在我想循环遍历 myMap 并获取所有键(A 类型)。我该怎么做?
我想通过循环从 myMap 获取所有键,并将它们发送到“void myFunction(A param){...}”。
最佳答案
这是基于问题标题的更通用的答案。
使用 entrySet() 解析键和值
HashMap<A, B> myMap = new HashMap<A, B>();
...
myMap.put(key, value);
...
for (Entry<A, B> e : myMap.entrySet()) {
A key = e.getKey();
B value = e.getValue();
}
//// or using an iterator:
// retrieve a set of the entries
Set<Entry<A, B>> entries = myMap.entrySet();
// parse the set
Iterator<Entry<A, B>> it = entries.iterator();
while(it.hasNext()) {
Entry<A, B> e = it.next();
A key = e.getKey();
B value = e.getValue();
}
使用keySet()解析键
HashMap<A, B> myMap = new HashMap<A, B>();
...
myMap.put(key, value);
...
for (A key : myMap.keySet()) {
B value = myMap.get(key); //get() is less efficient
} //than above e.getValue()
// for parsing using a Set.iterator see example above
查看有关问题 Performance considerations for keySet() and entrySet() of Map 的 entrySet()
与 keySet()
的更多详细信息.
使用 values() 解析值
HashMap<A, B> myMap = new HashMap<A, B>();
...
myMap.put(key, value);
...
for (B value : myMap.values()) {
...
}
//// or using an iterator:
// retrieve a collection of the values (type B)
Collection<B> c = myMap.values();
// parse the collection
Iterator<B> it = c.iterator();
while(it.hasNext())
B value = it.next();
}
关于java - Java中HashMap的解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9129090/