两种方式遍历HashMap

通过Map类的get(key)方法获取value时,会进行两次hashCode的计算,消耗CPU资源;而使用entrySet的方式,map对象会直接返回其保存key-value的原始数据结构对象,遍历过程无需进行错误代码中耗费时间的hashCode计算; 这在大数据量下,体现的尤为明显。

package com.bb.eoa.extend.yssp.controller;

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

public class T {
	public static void main(String[] args) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("str1", "str11");
		map.put("str2", "str22");
		map.put("str3", "str33");
		/**
		 * 第一种方式:通过Map类的get(key)方法获取value
		 */

		for (Iterator<String> ite = map.keySet().iterator(); ite.hasNext();) { // foreach输出
			Object key = ite.next();
			Object value = map.get(key);
			System.out.print(key);
			System.out.print("-->");
			System.out.print(value);
			System.out.println();
		}

		System.out.println("-----------");

		Set s = map.keySet(); // 普通方式输出
		Iterator i = s.iterator();
		while (i.hasNext()) {
			Object key = i.next();
			Object value = map.get(key);
			System.out.print(key);
			System.out.print("-->");
			System.out.print(value);
			System.out.println();
		}
		System.out.println("---------");
		/**
		 * 第二种方式:利用entrySet方式,map对象会直接返回其保存key-value的原始数据结构对象
		 */
		Set entry = map.entrySet();   //普通方式输出
		Iterator ite = entry.iterator();
		while (ite.hasNext()) {
			Map.Entry m = (Map.Entry) ite.next(); // Set中的每一个元素都是Map.Entry
			System.out.print(m.getKey() + "-->");
			System.out.println(m.getValue());
		}
		System.out.println("-----------"); 
		for (Iterator it = map.entrySet().iterator(); it.hasNext();) { // foreach输出
			Map.Entry e = (Map.Entry) it.next();
			System.out.print(e.getKey()+"-->");
			System.out.print(e.getValue());
			System.out.println();
		}	
	}
}


原文地址:https://www.cnblogs.com/itmyhome/p/4131577.html