HashMap的遍历

发现项目中每个人遍历map的方式都有所不同,有的用keySet,有的用entrySet,试了试,按原理是entrySet快。
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

public class HashMapTest {
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		HashMap hashmap = new HashMap();
		for (int i = 0; i < 5000; i++) {
			hashmap.put("k_" + i, "speed_"+ i);
		}
		
		keySetTest(hashmap);
		entrySetTest(hashmap);
		
		Map<String, String> paraMap = new HashMap<String, String>();
		paraMap.put("k1", "v1");
		paraMap.put("k2", "v2");
		
		//循环 keyset
		//Set<String> appFieldDefIds = paraMap.keySet();
		for (String appFieldDefId : paraMap.keySet()) {
		String values = paraMap.get(appFieldDefId);
		System.out.println(values);
		}
		//循环 entry
		for(Entry<String, String> entry : paraMap.entrySet()){
			String appFieldDefId = entry.getKey();
			String values = entry.getValue();
			System.out.println(values);
		}

	}
	
	@SuppressWarnings("unchecked")
	public static void keySetTest(HashMap hashmap) {
		long begin = Calendar.getInstance().getTimeInMillis();
		Iterator iterator = hashmap.keySet().iterator();
		while (iterator.hasNext()) {
			System.out.print(hashmap.get(iterator.next()));
		}
		System.out.println("keySet Time");
		System.out.println(Calendar.getInstance().getTimeInMillis() - begin);
	}
	
	@SuppressWarnings("unchecked")
	public static void entrySetTest(HashMap hashmap){
		long begin = Calendar.getInstance().getTimeInMillis();
		Iterator it = hashmap.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			System.out.print(entry.getValue());
		}
		System.out.println("Entry Time:");
		System.out.println(Calendar.getInstance().getTimeInMillis() - begin);
	}
	
	

}


keySet遍历了2次,一次是转为iterator,再利用HashMap的get(Object key)来取value值。
entryset遍历了第一次,他把key和value都放到了entry中。
按照Map的概念来看也应该是用entryset循环好一点,它本来就是key和value的值对。

你可能感兴趣的:(java)