java中遍历HashMap的方法

编程入门 行业动态 更新时间:2024-10-27 10:34:42

java中<a href=https://www.elefans.com/category/jswz/34/1771029.html style=遍历HashMap的方法"/>

java中遍历HashMap的方法

Java中,通常有两种遍历HashMap的方法,如下:

import java.util.*;public class MapTest {static HashMap<String, Integer> hashMap = new HashMap<String, Integer>();public static void main(String [] args) {hashMap.put("one", 1);hashMap.put("two", 2);hashMap.put("three", 3);hashMap.put("four", 4);hashMap.put("five", 5);Iterator iter = hashMap.entrySet().iterator();// the first method to travel the mapwhile (iter.hasNext()) {Map.Entry<String, Integer> entry = (Map.Entry<String, Integer>) iter.next();String key = entry.getKey();Integer value = entry.getValue();System.out.println(key + " " + value);}iter = hashMap.keySet().iterator();// the second method to travel the mapwhile (iter.hasNext()) {String key = (String) iter.next();Integer value = hashMap.get(key);System.out.println(key + " " + value);}} // close main()
}

第一种效率要高于第二种,应尽量使用第一种进行遍历。

更多推荐

java中遍历HashMap的方法

本文发布于:2023-06-19 15:34:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/787569.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:遍历   方法   java   HashMap

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!