遍历HashMap的七种方法

编程入门 行业动态 更新时间:2024-10-28 04:17:20

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

遍历HashMap的七种方法

直接上代码

/*** @Description* @Author 暴怒阿西* @Date 2022-11-15 15:22*/
public class HashMapTest2 {static HashMap<Integer, String> map = new HashMap<>();static {map.put(1, "Java");map.put(2, "PHP");map.put(3, "C#");map.put(4, "Golang");}//使用 iterator 遍历EntrySet@Testpublic void test1() {Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();while (iterator.hasNext()) {Map.Entry<Integer, String> entry = iterator.next();System.out.print(entry.getKey()+" ");System.out.println(entry.getValue());}}//使用 iterator 遍历KeySet@Testpublic void test2() {Iterator<Integer> iterator = map.keySet().iterator();while (iterator.hasNext()) {Integer key = iterator.next();System.out.print(key+" ");System.out.println(map.get(key));}}// forEach keySet@Testpublic void test3() {Set<Integer> keySet = map.keySet();for (Integer key : keySet) {System.out.print(key+" ");System.out.println(map.get(key));}}// forEach EntrySet@Testpublic void test4() {Set<Map.Entry<Integer, String>> entries = map.entrySet();for (Map.Entry<Integer, String> entry : entries) {System.out.print(entry.getKey()+" ");System.out.println(entry.getValue());}}// Lambda forEach@Testpublic void test5() {map.forEach((k,v)->{System.out.print(k+" ");System.out.println(v);});}//Streams 单线程@Testpublic void test6() {map.entrySet().stream().forEach((entry)->{System.out.print(entry.getKey()+" ");System.out.println(entry.getValue());});}//Stream 多线程@Testpublic void test7() {map.entrySet().parallelStream().forEach((entry)->{System.out.print(entry.getKey()+" ");System.out.println(entry.getValue());});}
}

更多推荐

遍历HashMap的七种方法

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

发布评论

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

>www.elefans.com

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