【发布时间】:2012-02-26 02:19:27
【问题描述】:
我有一个简单的问题。
我设置:
HashMap<A, B> myMap = new HashMap<A, B>();
...
myMap.put(...)
...
现在我想遍历 myMap 并获取所有键(A 类型)。我该怎么做?
我想通过循环从 myMap 中获取所有键,并将它们发送到“void myFunction(A param){...}”。
【问题讨论】:
我有一个简单的问题。
我设置:
HashMap<A, B> myMap = new HashMap<A, B>();
...
myMap.put(...)
...
现在我想遍历 myMap 并获取所有键(A 类型)。我该怎么做?
我想通过循环从 myMap 中获取所有键,并将它们发送到“void myFunction(A param){...}”。
【问题讨论】:
map.keySet() 将返回包含所有键的集合.. 从这里您可以解析集合并获取所有键
【讨论】:
myMap.keySet() ?不确定你的实际意思。
【讨论】:
获取密钥集的方法如下:
Set<A> keys = myMap.keySet();
我不知道“传递”是什么意思。我也不知道“解析”对于 HashMap 意味着什么。除了从地图中取出钥匙之外,这个问题毫无意义。投票结束。
【讨论】:
在将映射传递到您要传递到的任何位置后,以映射结尾的方法/类将进行以下调用以获取映射中的键集。
Set<A> keys = myMap.keySet();
【讨论】:
您可以使用Google Guava 过滤您的收藏。过滤、排序等的例子可以在here找到。
【讨论】:
如果您想从地图中获取所有键值对
使用 map.keyset() 它将返回集合中的所有键
现在你可以使用迭代器来迭代所有键值
并在 map.get(key) 中使用它。
【讨论】:
这是基于问题标题的更通用的答案。
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();
}
【讨论】:
如果你不想从你的地图中移除元素,你可以使用这个:
for(A k:myMap.keySet()) {
//the correspending value is myMap.get(k))
}
但是,如果您想从地图中删除元素,则必须使用迭代器。这里举个例子给你看:
public class TutoMap {
public static void main(String[] args) {
//Create a map
Map<Integer, String> map = new HashMap<>();
//add some elements to the map
map.put(0, "a");
map.put(5, "b");
map.put(3, "c");
map.put(4, "e");
map.put(10, "d");
//get the iterator of the Entry set
Iterator iter = map.entrySet().iterator();
//try to remove element of key = 4
while (iter.hasNext()) {
Map.Entry<Integer, String> ele = (Map.Entry<Integer, String>) iter.next();
if (ele.getKey() == 4) {
iter.remove();
}
}
}
}
【讨论】: