两种方式遍历HashMap
来源:互联网 发布:图像坐标轴 知乎 编辑:程序博客网 时间:2024/05/17 03:01
通过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();
- }
- }
- }
0 0
- 两种方式遍历HashMap
- 两种方式遍历HashMap
- HashMap两种遍历方式
- 两种方式遍历HashMap
- HashMap遍历的两种方式
- 遍历HashMap的常用两种方式
- HashMap遍历的两种方式
- HashMap遍历的两种方式
- HashMap遍历的两种方式
- HashMap遍历的两种方式
- hashmap遍历的两种方式
- HashMap遍历的两种方式
- HashMap遍历的两种方式
- 遍历HashMap的两种方式
- HashMap遍历的两种方式
- HashMap遍历的两种方式
- HashMap遍历的两种方式
- HashMap遍历的两种方式
- content-type头 (MIME类型)
- 顶级pom和子pom版本批量修改
- Android开发的前景分析——之你为何看好Android?
- mysql事物级别详解
- Android 判断SD卡是否存在及容量查询
- 两种方式遍历HashMap
- Linux 命令
- HDU 2475 Box 树型转线型 + 伸展树
- 反向解析引发的访问慢问题的解决
- EasyUI的DataGrid日期列(datebox)正确显示json时间格式
- 关于c语言中的强制类型转换
- 网站翻译插件
- 高仿交通银行手机客户端界面
- 72_leetcode_Construct Binary Tree from Preorder and Inorder Traversal