HashMap的四种访问方式

时间:2022-09-13 20:00:37

第一种:通过Map.entrySet使用iterator遍历key和value

public void visit_1(HashMap<String,Integer> hm){
Iterator<Map.Entry<String,Integer>> it = hm.entrySet().iterator();
while(it.hasNext()){
Map.Entry<String ,Integer> entry = it.next();
String key = entry.getKey();
Integer value = entry.getValue();
}
}

第二种:通过Key来遍历value

public void visit_2(HashMap<String,Integer> hm){
for (String key:hm.keySet()){
Integer value = hm.get(key);
}
}

第三种:通过Map.Entry遍历key和value

 public void visit_3(HashMap<String,Integer> hm){
for(Map.Entry<String,Integer> entry:hm.entrySet()){
String key = entry.getKey();
Integer value = entry.getValue();
}
}

第四种:通过Map.keySet使用iterator遍历key和value

public void visit_4(HashMap<Integer,String> hm){
long startTime = System.currentTimeMillis();
Iterator<Integer> it = hm.keySet().iterator();
while(it.hasNext()){
Integer key = it.next();
String value = hm.get(key);
}
System.out.println("visit_4 10000000 entry:"
+ (System.currentTimeMillis()-startTime) + " milli seconds");
}

四种方法比较:

package chapter08.c86.c862;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
* Created by ceoicac on 2017/8/12 10:22.
*/

public class HashMapVisitTest {
public void visit_1(HashMap<Integer,String> hm){
long startTime = System.currentTimeMillis();
Iterator<Map.Entry<Integer,String>> it = hm.entrySet().iterator();
while(it.hasNext()){
Map.Entry<Integer,String> entry = it.next();
Integer key = entry.getKey();
String value = entry.getValue();
}
System.out.println("visit_1 10000000 entry:"
+ (System.currentTimeMillis()-startTime) + " milli seconds");
}
public void visit_2(HashMap<Integer,String> hm){
long startTime = System.currentTimeMillis();
for (Integer key:hm.keySet()){
String value = hm.get(key);
}
System.out.println("visit_1 10000000 entry:"
+ (System.currentTimeMillis()-startTime) + " milli seconds");
}
public void visit_3(HashMap<Integer,String> hm){
long startTime = System.currentTimeMillis();
for(Map.Entry<Integer,String> entry : hm.entrySet()){
Integer key = entry.getKey();
String value = entry.getValue();
}
System.out.println("visit_1 10000000 entry:"
+ (System.currentTimeMillis()-startTime) + " milli seconds");
}
public void visit_4(HashMap<Integer,String> hm){
long startTime = System.currentTimeMillis();
Iterator<Integer> it = hm.keySet().iterator();
while(it.hasNext()){
Integer key = it.next();
String value = hm.get(key);
}
System.out.println("visit_1 10000000 entry:"
+ (System.currentTimeMillis()-startTime) + " milli seconds");
}
public static void main(String [] args){
HashMap<Integer,String> hm = new HashMap<>();
for(int i = 1;i <= 10000000;++i){
hm.put(i,"num: " + i);
}
new HashMapVisitTest().visit_1(hm);
new HashMapVisitTest().visit_2(hm);
new HashMapVisitTest().visit_3(hm);
new HashMapVisitTest().visit_4(hm);

}
}

结果:
HashMap的四种访问方式