uri*_*iel 2 java parsing key hashmap
我有一个简单的问题.
我设置:
HashMap<A, B> myMap = new HashMap<A, B>();
...
myMap.put(...)
...
Run Code Online (Sandbox Code Playgroud)
现在我想循环遍历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();
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
查看有关entrySet()vs keySet()on question的更多详细信息对于Map的keySet()和entrySet()的性能注意事项.
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();
}
Run Code Online (Sandbox Code Playgroud)
以下是获取密钥集的方法:
Set<A> keys = myMap.keySet();
Run Code Online (Sandbox Code Playgroud)
我不知道“传递”是什么意思。我也不知道“解析”对 HashMap 意味着什么。除了从 Map 中取出钥匙之外,这个问题没有任何意义。投票结束。