HashMap的四种遍历方法

2015/07/11 19:55

《冬夜读书示子聿》

（南宋）陆游 宁宗庄元五年（公元1199年）底

RT，测试程序

package javay.test.java;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

/**

* HashMap的四种遍历方法

* @author DBJ(dubenju@126.com)

*/

public class TestHashMap {

public static HashMap<String, String> makeData() {

HashMap<String, String> map = new HashMap<String, String>();

for (int i = 0; i < 1000000; i ++) {

String kv = String.valueOf(i);

map.put(kv, kv);

}

return map;

}

/**

* 使用Iterator遍历

* @param map

*/

public static void testa(HashMap<String, String> map) {

long a = System.currentTimeMillis();

Iterator<Map.Entry<String, String>> iter = map.entrySet().iterator();

while (iter.hasNext()) {

Map.Entry<String, String> entry = iter.next();

// System.out.println("Key = " + entry.getKey() + "Value = " + entry.getValue());

String key = entry.getKey();

String value = entry.getValue();

}

System.out.println("耗时：" + (System.currentTimeMillis() - a));

}

/**

* 在for-each循环中使用entries来遍历★

* @param map

*/

public static void testb(HashMap<String, String> map) {

long a = System.currentTimeMillis();

for (Map.Entry<String, String> entry :map.entrySet()) {

// System.out.println("Key = " + entry.getKey() + "Value = " + entry.getValue());

String key = entry.getKey();

String value = entry.getValue();

}

System.out.println("耗时：" + (System.currentTimeMillis() - a));

}

/**

* 通过键找值遍历（效率低）

* @param map

*/

public static void testc(HashMap<String, String> map) {

long a = System.currentTimeMillis();

Iterator<String> iter = map.keySet().iterator();

while (iter.hasNext()) {

String key = iter.next();

// System.out.println("Key = " + key + "Value = " + map.get(key));

String value = map.get(key);

}

System.out.println("耗时：" + (System.currentTimeMillis() - a));

}

/**

* 在for-each循环中遍历keys或values★

* @param map

*/

public static void testd(HashMap<String, String> map) {

long a = System.currentTimeMillis();

//遍历map中的键

for (String key : map.keySet()) {

// System.out.println("Key = " + key);

String k = key;

}

System.out.println("耗时：" + (System.currentTimeMillis() - a));

a = System.currentTimeMillis();

//遍历map中的值

for (String value : map.values()) {

// System.out.println("Value = " + value);

String v = value;

}

System.out.println("耗时：" + (System.currentTimeMillis() - a));

}

public static void main(String[] args) {

HashMap<String, String>  dat = makeData();

testa(dat); // 使用Iterator遍历

testb(dat); // 在for-each循环中使用entries来遍历★既要key也要value的话

testc(dat); // 通过键找值遍历（效率低）

testd(dat); // 在for-each循环中遍历keys或values★只遍历key/value的话

}

}

0
20 收藏

0 评论
20 收藏
0