Map作为Java的一个基本集合类,在很多场所都会使用到它。在使用Map时,会经常会遇到需要遍历整个Map情况。遍历Map时,主要使用的是EntrySet以及KeySet这两种遍历方法。
以下是实现两种遍历方式的代码:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* 遍历Map
*/
public class IterateMapDemo {
/**
* 主函数
* @param args
*/
public static void main(String[] args) {
Map<String, String> areaMap = new HashMap<String, String>();
areaMap.put("Beijing", "北京");
areaMap.put("Shanghai", "上海");
areaMap.put("Tianjin", "天津");
// 遍历
keySetIterateMap(areaMap);
entrySetIterateMap(areaMap);
}
/**
* keySet方式遍历
* @param mapInfo
*/
private static void keySetIterateMap(Map<String, String> mapInfo) {
// for循环遍历
Set<String> keySet = mapInfo.keySet();
for (String key : keySet) {
System.out.println("KeySet,For循环遍历,Key:" + key + "Value:" + mapInfo.get(key));
}
// 迭代器遍历
Iterator<String> it = mapInfo.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
System.out.println("KeySet,Iterator遍历,Key:" + key + "Value:" + mapInfo.get(key));
}
}
/**
* entrySet遍历
* @param mapInfo
*/
private static void entrySetIterateMap(Map<String, String> mapInfo) {
// for循环遍历
Set<Map.Entry<String, String>> entrySet = mapInfo.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
System.out.println("EntrySet,For循环遍历,Key:" + entry.getKey() + "Value:" + entry.getValue());
}
// 迭代器遍历
Iterator<Map.Entry<String, String>> it = mapInfo.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
System.out.println("EntrySet,Iterator循环遍历,Key:" + entry.getKey() + "Value:" + entry.getValue());
}
}
}
性能对比
在数据量少的时候,两种遍历自然差距不会太大。但是当数据量增加的时候,就需要对比下哪种遍历方式更快了。
以下是Map中具有1百万条数据时,两种遍历方式的耗时信息(单位ms):
可以看出,EntrySet遍历的速度要比keySet方法要快哦。这是因为使用keySet遍历时,当使用key值取得Map中的Value时,Map又遍历了一遍。而EntrySe时,由于EntrySet本身就是key-value结构,所以直接将Map的key-value给取出来了,自然速度就要快上一些。另外,使用迭代器遍历的话速度也会有一些提升。