1、entrySet(),效率高,常用,推荐
for(Map.Entry<String, String> entry:map.entrySet()){
System.out.println(entry.getKey()+"—>"+entry.getValue());
}
2、迭代
Set set = map.entrySet();
Iterator i = set.iterator();
while(i.hasNext()){
Map.Entry<String, String> entry1=(Map.Entry<String, String>)i.next();
System.out.println(entry1.getKey()+"=="+entry1.getValue());
}
3、keySet\value 方便
for (String str: map.values()) { //获取值
System.out.println(“value:” + str);
}
for (String str: map.keySet()) {//获取key
System.out.println(“key:” + str + “,value:” + map.get(str));
}
4、Lambda,最简洁
map.foreach((key,map) -> {
System.out.println(key + “:” + value);
})
测试:
public static void main(String[] args) {
Map<String,String> map = new HashMap<>();
//1千万条数据遍历
for (int i = 0; i < 10000000; i++) {
map.put(i+"", "1");
}
long startTime1=System.currentTimeMillis();
for(Map.Entry<String, String> entry:map.entrySet()){
//System.out.println(entry.getKey()+"--->"+entry.getValue());
}
long endTime1=System.currentTimeMillis();
float excTime1=(float)(endTime1-startTime1)/1000;
System.out.println("entrySet()执行时间:"+excTime1+"s");
long startTime2=System.currentTimeMillis();
Set set = map.entrySet();
Iterator i = set.iterator();
while(i.hasNext()){
Map.Entry<String, String> entry1=(Map.Entry<String, String>)i.next();
//System.out.println(entry1.getKey()+"=="+entry1.getValue());
}
long endTime2=System.currentTimeMillis();
float excTime2=(float)(endTime2-startTime2)/1000;
System.out.println("Iterator执行时间:"+excTime2+"s");
long startTime3=System.currentTimeMillis();
for (Object str: map.keySet()) {
//System.out.println("key:" + str + ",value:" + map.get(str));
}
long endTime3=System.currentTimeMillis();
float excTime3=(float)(endTime3-startTime3)/1000;
System.out.println("keySet执行时间:"+excTime3+"s");
long startTime4=System.currentTimeMillis();
map.forEach((key,value) -> {
//System.out.println(key + ":" + value);
});
long endTime4=System.currentTimeMillis();
float excTime4=(float)(endTime4-startTime4)/1000;
System.out.println("forEach执行时间:"+excTime4+"s");
}
结果
entrySet()执行时间:0.193s
Iterator执行时间:0.176s
keySet执行时间:0.177s
forEach执行时间:0.224s