Java 遍历 HashMap
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1066589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterate through a HashMap
采纳答案by karim79
Iterate through the entrySet()
like so:
entrySet()
像这样迭代:
public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
}
Read more about Map
.
阅读更多关于Map
.
回答by harto
If you're only interested in the keys, you can iterate through the keySet()
of the map:
如果您只对键感兴趣,则可以遍历keySet()
地图的 :
Map<String, Object> map = ...;
for (String key : map.keySet()) {
// ...
}
If you only need the values, use values()
:
如果您只需要这些值,请使用values()
:
for (Object value : map.values()) {
// ...
}
Finally, if you want both the key and value, use entrySet()
:
最后,如果您想要键和值,请使用entrySet()
:
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// ...
}
One caveat: if you want to remove items mid-iteration, you'll need to do so via an Iterator (see karim79's answer). However, changing item values is OK (see Map.Entry
).
一个警告:如果你想在迭代中删除项目,你需要通过一个迭代器来做(参见karim79 的答案)。但是,更改项目值是可以的(请参阅 参考资料Map.Entry
)。
回答by Gary Kephart
Depends. If you know you're going to need both the key and the value of every entry, then go through the entrySet
. If you just need the values, then there's the values()
method. And if you just need the keys, then use keyset()
.
要看。如果您知道您将需要每个条目的键和值,则通过entrySet
. 如果您只需要这些值,那么就有values()
方法。如果您只需要密钥,请使用keyset()
.
A bad practice would be to iterate through all of the keys, and then within the loop, always do map.get(key)
to get the value. If you're doing that, then the first option I wrote is for you.
一个不好的做法是遍历所有的键,然后在循环中,总是这样做map.get(key)
来获取值。如果你这样做,那么我写的第一个选项就是给你的。
回答by codethulhu
You can iterate through the entries in a Map
in several ways. Get each key and value like this:
您可以通过Map
多种方式遍历条目。像这样获取每个键和值:
Map<?,?> map = new HashMap<Object, Object>();
for(Entry<?, ?> e: map.entrySet()){
System.out.println("Key " + e.getKey());
System.out.println("Value " + e.getValue());
}
Or you can get the list of keys with
或者您可以使用以下命令获取密钥列表
Collection<?> keys = map.keySet();
for(Object key: keys){
System.out.println("Key " + key);
System.out.println("Value " + map.get(key));
}
If you just want to get all of the values and aren't concerned with the keys, you can use:
如果您只想获取所有值而不关心键,您可以使用:
Collection<?> values = map.values();
回答by jkarretero
Smarter:
更聪明:
for (String key : hashMap.keySet()) {
System.out.println("Key: " + key + ", Value: " + map.get(key));
}
回答by gabor
for (Map.Entry<String, String> item : hashMap.entrySet()) {
String key = item.getKey();
String value = item.getValue();
}
回答by arvind
Extracted from the reference How to Iterate Over a Map in Java:
摘自参考How to Iterate Over a Map in Java:
There are several ways of iterating over a Map
in Java. Let's go over the most common methods and review their advantages and disadvantages. Since all maps in Java implement the Map interface, the following techniques will work for any map implementation (HashMap
, TreeMap
, LinkedHashMap
, Hashtable
, etc.)
Map
在 Java 中有几种迭代 a 的方法。让我们回顾一下最常用的方法并回顾它们的优缺点。由于Java中所有地图实现Map接口,下面的技术适用于任何地图的实施工作(HashMap
,TreeMap
,LinkedHashMap
,Hashtable
,等)
Method #1: Iterating over entries using a For-Each loop.
方法 #1:使用 For-Each 循环遍历条目。
This is the most common method and is preferable in most cases. It should be used if you need both map keys and values in the loop.
这是最常用的方法,在大多数情况下更可取。如果您需要循环中的映射键和值,则应该使用它。
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Note that the For-Each loop was introduced in Java 5, so this method is working only in newer versions of the language. Also a For-Each loop will throw NullPointerException
if you try to iterate over a map that is null, so before iterating you should always check for null references.
请注意,For-Each 循环是在 Java 5 中引入的,因此此方法仅适用于该语言的较新版本。NullPointerException
如果您尝试迭代一个为空的映射,For-Each 循环也会抛出,因此在迭代之前,您应该始终检查空引用。
Method #2: Iterating over keys or values using a For-Each loop.
方法#2:使用 For-Each 循环迭代键或值。
If you need only keys or values from the map, you can iterate over keySet or values instead of entrySet.
如果您只需要映射中的键或值,您可以迭代 keySet 或值而不是 entrySet。
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
// Iterating over keys only
for (Integer key : map.keySet()) {
System.out.println("Key = " + key);
}
// Iterating over values only
for (Integer value : map.values()) {
System.out.println("Value = " + value);
}
This method gives a slight performance advantage over entrySet
iteration (about 10% faster) and is more clean.
这种方法比entrySet
迭代具有轻微的性能优势(大约快 10%)并且更干净。
Method #3: Iterating using Iterator.
方法#3:使用迭代器进行迭代。
Using Generics:
使用泛型:
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<Integer, Integer> entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Without Generics:
没有泛型:
Map map = new HashMap();
Iterator entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
Integer key = (Integer)entry.getKey();
Integer value = (Integer)entry.getValue();
System.out.println("Key = " + key + ", Value = " + value);
}
You can also use same technique to iterate over keySet
or values.
您还可以使用相同的技术来迭代keySet
或 值。
This method might look redundant, but it has its own advantages. First of all, it is the only way to iterate over a map in older versions of Java. The other important feature is that it is the only method that allows you to remove entries from the map during iteration by calling iterator.remove()
. If you try to do this during For-Each iteration you will get "unpredictable results" according to Javadoc.
这种方法可能看起来多余,但它有自己的优点。首先,它是在旧版 Java 中迭代地图的唯一方法。另一个重要特性是它是唯一允许您在迭代期间通过调用从地图中删除条目的方法iterator.remove()
。如果您尝试在 For-Each 迭代期间执行此操作,您将根据Javadoc获得“不可预测的结果” 。
From a performance point of view this method is equal to a For-Each iteration.
从性能的角度来看,这种方法等同于 For-Each 迭代。
Method #4: Iterating over keys and searching for values (inefficient).
方法#4:迭代键并搜索值(低效)。
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer key : map.keySet()) {
Integer value = map.get(key);
System.out.println("Key = " + key + ", Value = " + value);
}
This might look like a cleaner alternative for method #1, but in practice it is pretty slow and inefficient as getting values by a key might be time-consuming (this method in different Map implementations is 20%-200% slower than method #1). If you have FindBugs installed, it will detect this and warn you about inefficient iteration. This method should be avoided.
这可能看起来像是方法 #1 的更简洁的替代方案,但实际上它非常缓慢且效率低下,因为通过键获取值可能很耗时(不同 Map 实现中的此方法比方法 #1 慢 20%-200% )。如果您安装了 FindBugs,它会检测到这一点并警告您迭代效率低下。这种方法应该避免。
Conclusion:
结论:
If you need only keys or values from the map, use method #2. If you are stuck with older version of Java (less than 5) or planning to remove entries during iteration, you have to use method #3. Otherwise use method #1.
如果您只需要映射中的键或值,请使用方法 #2。如果您坚持使用旧版本的 Java(少于 5 个)或计划在迭代期间删除条目,则必须使用方法 #3。否则使用方法#1。