Map常用遍历方法
HashMap常用遍历方法
1.for循环中使用entries实现Map的遍历
@Test public void fun1(){ Map<String, String> map = new HashMap<String, String>(); map.put("Java入门教程", "http://c.biancheng.net/java/"); map.put("C语言入门教程", "http://c.biancheng.net/c/"); for (Map.Entry<String, String> entry : map.entrySet()) { String mapKey = entry.getKey(); String mapValue = entry.getValue(); System.out.println(mapKey + ":" + mapValue); } }
2.使用迭代器(Iterator)遍历
public void fun2(){ Map<String, String> map = new HashMap<String, String>(); map.put("Java入门教程", "http://c.biancheng.net/java/"); map.put("C语言入门教程", "http://c.biancheng.net/c/"); Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, String> entry = entries.next(); String key = entry.getKey(); String value = entry.getValue(); System.out.println(key + ":" + value); } }
二者耗时比较
@Test public void fun3(){ Map<Integer, Integer> map = new HashMap<Integer, Integer>(); Random random =new Random(); for (int a=0;a<1000000;a++){ int b=random.nextInt(200); map.put(a,b); } long t1= System.currentTimeMillis(); for (Map.Entry<Integer, Integer> entry : map.entrySet()) { Integer mapKey = entry.getKey(); Integer mapValue = entry.getValue(); System.out.println(mapKey + ":" + mapValue); } long t2= System.currentTimeMillis(); System.out.print("for循环中使用entries实现Map的遍历耗时为:"); System.out.println((t2 - t1)+"毫秒"); }
for循环中使用entries实现Map的遍历耗时为:9937毫秒
@Test public void fun4(){ Map<Integer, Integer> map = new HashMap<Integer, Integer>(); Random random =new Random(); for (int a=0;a<1000000;a++){ int b=random.nextInt(200); map.put(a,b); } long t1= System.currentTimeMillis(); Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<Integer, Integer> entry = entries.next(); Integer key = entry.getKey(); Integer value = entry.getValue(); System.out.println(key + ":" + value); } long t2= System.currentTimeMillis(); System.out.print("使用迭代器(Iterator)遍历耗时为:"); System.out.println((t2 - t1)+"毫秒"); }
使用迭代器(Iterator)遍历耗时为:8554毫秒
经过代码测试,当数据量特别大时,迭代器的耗时相比较而言小一些