How to Iterate Over a Map in Java
2013-03-25 17:57
507 查看
There are several ways of iterating over a
following techniques will work for any map implementation (
etc.)
This is the most common method and is preferable in most cases. Should be used if you need both map keys and values in the loop.
Note that For-Each loop was introduced in Java 5 so this method is working only in newer versions of the language. Also For-Each loop will throw
is
If you need only keys or values from the map, you can iterate over
This method gives slight performance advantage over
Using Generics:
Without Generics:
You can also use same technique to iterate over
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
From performance point of view this method is equal to For-Each iteration.
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
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.
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.
Method 1://输出Map中的键值对
Map<String,String> map = new HashMap<String,String>();
for(Map.Entry<String,String> entry : map.entrySet()){
System.out.println("Key=" + entry.getKey() + ", Value = " + entry.getValue());
}
Method 2://只需要Map中的键 或者 值 则使用此方法
Map<String,String> map = new Map<String,String>();
//Iterating over keys only
for(String key:map.keySet()){
System.out.println("Key="+key);
}
//Iterating over values only
for(String value:map.values()){
System.out.println("Value="+value);
}
Mapin Java. Lets go over the most common methods and review their advantages and disadvantages. Since all maps in Java implement
Mapinterface,
following techniques will work for any map implementation (
HashMap,
TreeMap,
LinkedHashMap,
Hashtable,
etc.)
Method #1: Iterating over entries using For-Each loop.
This is the most common method and is preferable in most cases. 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 For-Each loop was introduced in Java 5 so this method is working only in newer versions of the language. Also For-Each loop will throw
NullPointerExceptionif you try to iterate over a map that
is
null, so before iterating you should always check for
nullreferences.
Method #2: Iterating over keys or values using For-Each loop.
If you need only keys or values from the map, you can iterate over keySetor
valuesinstead of
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 slight performance advantage over
entrySetiteration (about 10% faster) and is more clean.
Method #3: Iterating using Iterator
.
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
keySetor
values.
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.
From performance point of view this method is equal to For-Each iteration.
Method #4: Iterating over keys and searching for values (inefficient).
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
Mapimplementations
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.
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.Method 1://输出Map中的键值对
Map<String,String> map = new HashMap<String,String>();
for(Map.Entry<String,String> entry : map.entrySet()){
System.out.println("Key=" + entry.getKey() + ", Value = " + entry.getValue());
}
Method 2://只需要Map中的键 或者 值 则使用此方法
Map<String,String> map = new Map<String,String>();
//Iterating over keys only
for(String key:map.keySet()){
System.out.println("Key="+key);
}
//Iterating over values only
for(String value:map.values()){
System.out.println("Value="+value);
}
相关文章推荐
- How to Iterate Over a Map in Java
- How to Iterate Over a Map in Java
- How to Iterate Over a Map in Java?(如何遍历Map)
- How to Iterate Over a Map in Java
- How to Iterate over Array in Java 1.5 using foreach loop Example
- Notes: How to iterate a map in Java
- Notes: How to iterate a map in Java
- Notes: How to iterate a map in Java
- Notes: How to iterate a map in Java
- 4 example to Iterate over HashMap, Hashtable or any Map in Java
- Notes: How to iterate a map in Java
- Notes: How to iterate a map in Java
- Notes: How to iterate a map in Java
- Don't know how to iterate over supplied "items" in <forEach>
- Don't know how to iterate over supplied "items" in <forEach>
- How to implement common datastructures (List, Stack, Map) in plain Java - Tutorial
- How to solve "java.lang.VerifyError: Expecting a stackmap frame at branch target 6 in method"
- Don't know how to iterate over supplied "items" in <forEach>报错解决
- 【跟着stackoverflow学Pandas】How to iterate over rows in a DataFrame in Pandas-DataFrame按行迭代
- How to send a list of files over a socket in Java