import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.Random;
public class HashMapTest {
private static final String allChar = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String letterChar = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
// private static final String numberChar="0123456789";
public static void main(String args[]) {
System.out.println("1、生成1万条随机记录遍历结果(执行10次)");
executeHashMapTest(10, 10000);
System.out.println("2、生成10万条随机记录遍历结果(执行10次)");
executeHashMapTest(10, 100000);
System.out.println("3、生成50万条随机记录遍历结果(执行10次)");
executeHashMapTest(10, 500000);
}
public static void executeHashMapTest(int executions, int count) {
// for(int i=0;i<executions;i++){
// System.out.println("-----------第"+i+1+"次-------------------");
Map<String, String> map = new HashMap<String, String>();
for (int j = 0; j < count; j++) {
map.put(generateRandomString(8), "HashMapTest");
}
interatorHashMap(map, 1);
// interatorHashMap(map,2);
// interatorHashMap(map,3);
// interatorHashMap(map, 4);
interatorHashMap(map, 6);
// }
}
public static void interatorHashMap(Map<String, String> map, int method) {
long start = System.currentTimeMillis();
switch (method) {
case 1: {
/**
* 当需要遍历hashmap的时候,请尽量使用entrySet,而不要用keySet,entrySet的效率要比keySet高,
* 实际上使用entrySet是只需要遍历一次hash
* ,即将key和value的映射关系放入到entry中,再取之;而keySet需要两次遍历hash
* ,第一次取所有的key,第二次用key去取出对应的value。
*/
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
Object key = entry.getKey();
Object value = entry.getValue();
// System.out.println(key + "," + value);
}
}
break;
// case 2:{
// Iterator<String> it=map.keySet().iterator();
// while(it.hasNext()){
// Object key=it.next();
// Object value=map.get(it.next());
// }
// }
// break;
// case 3:{
// Set<String> set = map.keySet();
// for (String s : set) {
// String value=s;
// }
// }
// break;
// case 4: {
// Set<Map.Entry<String, String>> entrySet = map.entrySet();
// for (Map.Entry<String, String> entry : entrySet) {
// String value = entry.getKey();
// }
// }
// break;
case 6: {
Iterator<String> it = map.values().iterator();
while (it.hasNext()) {
String key = it.next();
String value=map.get(key);
// System.out.println(key+","+map.get(key));
}
}
break;
}
long end = System.currentTimeMillis();
System.out.println("Method " + method + ":" + (end - start) + "ms");
}
public static String generateRandomString(int length) {
StringBuffer sb = new StringBuffer();
Random random = new Random();
for (int i = 0; i < length; i++) {
sb.append(allChar.charAt(random.nextInt(letterChar.length())));
}
return sb.toString();
}
}