遍历HashMap的几种方法

编程入门 行业动态 更新时间:2024-10-27 16:25:56

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

遍历HashMap的几种方法

有如下几种方法:

1. 通过keyset

2. 通过 Map.entrySet().iterator()

3. 通过foreach ---- Map.entryset, 当hashmap很大时,推荐使用这种方式。

4. 通过Valueset

public static void main(String[] args) {HashMap<Integer, String> hashmap = new HashMap<>();hashmap.put(1,"gogo");hashmap.put(2,"wade");hashmap.put(3,"james");hashmap.put(4,"curry");// 1. 通过Map.keySet遍历key和value:for (int key : hashmap.keySet()){System.out.println("key: "+ key + "; value: " + hashmap.get(key));}//2. 通过Map.entrySet使用iterator遍历key和value:Iterator<Map.Entry<Integer, String>> it = hashmap.entrySet().iterator();while (it.hasNext()){Map.Entry<Integer, String> entry = it.next();System.out.println("key: "+ entry.getKey() + "; value: " + entry.getValue());}//3. 通过Map.entrySet遍历key和valuefor(Map.Entry<Integer, String> entry : hashmap.entrySet()){System.out.println("key: "+ entry.getKey() + "; value: " + entry.getValue());}//4. 通过Map.values()遍历所有的value,但不能遍历keyfor (String value : hashmap.values()) {System.out.println("value: "+value);}}

更多推荐

遍历HashMap的几种方法

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

发布评论

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

>www.elefans.com

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