遍历HashMap的四种方法
来源:互联网 发布:java设计模式书籍 知乎 编辑:程序博客网 时间:2024/06/06 03:47
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("1", "value1");
map.put("2", "value2");
map.put("3", "value3");
//第一种:普遍使用,二次取值
System.out.println("通过Map.keySet遍历key和value:");
for (String key : map.keySet()) {
System.out.println("key= "+ key + " and value= " + map.get(key));
}
//第二种
System.out.println("通过Map.entrySet使用iterator遍历key和value:");
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
//第三种:推荐,尤其是容量大时
System.out.println("通过Map.entrySet遍历key和value");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
//第四种
System.out.println("通过Map.values()遍历所有的value,但不能遍历key");
for (String v : map.values()) {
System.out.println("value= " + v);
}
}
第一种:
Map map = new HashMap();Iterator iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
Object val = entry.getValue();
}
效率高,以后一定要使用此种方式!
第二种:
Map map = new HashMap();
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
Object key = iter.next();
Object val = map.get(key);
}
效率低,以后尽量少使用!
0 0
- 遍历HashMap的四种方法
- 遍历HashMap的四种方法
- HashMap遍历的四种方法
- 遍历HashMap的四种方法
- 遍历HashMap的四种方法
- 遍历HashMap的四种方法
- 遍历HashMap的四种方法
- 遍历HashMap的四种方法
- HashMap的四种遍历
- hashMap的四种遍历
- 遍历HashMap的四种
- HashMap的四种遍历方法,及效率比较
- HashMap的四种循环遍历方式
- 遍历HashMap的四种方式
- HashMap的四种遍历方式
- Java -- HashMap的四种遍历方式
- 遍历HashMap的四种方式
- 遍历Hashmap的四种方式
- JavaScript中的Date对象
- DHTMLX-Form
- Python高级技巧
- PHP 模板 smarty 逻辑运算符号
- 解决Centos关闭You have new mail in /var/spool/mail/root提示
- 遍历HashMap的四种方法
- 【杭电】 1001 Sum Problem
- 现代化Web的微服务架构最佳实践全景
- 深度增强学习方向论文整理
- [Android Studio 权威教程]打包、生成jks密钥、签名Apk、多渠道打包
- 使用百度地图SDK实现定位功能,定位你当前的位置
- ndk之AAssetManager
- 使用润乾参数模板后如何对参数进行二次处理
- Linux命令--sysctl