Java8⾼效遍历map_Java8中Map的遍历⽅式总结
1 2 3 4 5 6 7 8 9 10 11 | public class LambdaMap { private Map map = new HashMap<>(); @Before public void initData() { map.put( "key1" , "value1" ); map.put( "key2" , "value2" ); map.put( "key3" , "value3" ); map.put( "key4" , 4 ); map.put( "key5" , 5 ); map.put( "key5" , 'h' ); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 | /** * 遍历Map的⽅式⼀ * 通过Map.keySet遍历key和value */ @Test public void testErgodicWayOne() { System.out.println( "---------------------Before JAVA8 ------------------------------" ); for (String key : map.keySet()) { System.out.println( "map.get(" + key + ") = " + map.get(key)); } System.out.println( "---------------------JAVA8 ------------------------------" ); map.keySet().forEach(key -> System.out.println( "map.get(" + key + ") = " + map.get(key))); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | /** * 遍历Map第⼆种 * 通过Map.entrySet使⽤Iterator遍历key和value */ @Test public void testErgodicWayTwo() { System.out.println( "---------------------Before JAVA8 ------------------------------" ); Iterator> iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = iterator.next(); System.out.println( "key:value = " + entry.getKey() + ":" + entry.getValue()); } System.out.println( "---------------------JAVA8 ------------------------------" ); map.entrySet().iterator().forEachRemaining(item -> System.out.println( "key:value=" + item.getKey() + ":" + item.getValue())); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 | /** * 遍历Map第三种 * 通过Map.entrySet遍历key和value,在⼤容量时推荐使⽤ */ @Test public void testErgodicWayThree() { System.out.println( "---------------------Before JAVA8 ------------------------------" ); for (Map.Entry entry : map.entrySet()) { System.out.println( "key:value = " + entry.getKey() + ":" + entry.getValue()); } System.out.println( "---------------------JAVA8 ------------------------------" ); map.entrySet().forEach(entry -> System.out.println( "key:value = " + entry.getKey() + ":" + entry.getValue())); } |
1 2 3 4 5 6 7 | System.out.println( "---------------------Before JAVA8 ------------------------------" ); for (Object value : map.values()) { System.out.println( "map.value = " + value); } System.out.println( "---------------------JAVA8 ------------------------------" ); map.values().forEach(System.out::println); // 等价于map.values().forEach(value -> System.out.println(value)); } |
1 2 3 4 5 6 7 8 9 10 | /** * 遍历Map第五种 * 通过k,v遍历,Java8独有的 */ @Test public void testErgodicWayFive() { System.out.println( "---------------------Only JAVA8 ------------------------------" ); map.forEach((k, v) -> System.out.println( "key:value = " + k + ":" + v)); } } |
Java Map各遍历⽅式的性能⽐较
1. 阐述 对于Java中Map的遍历⽅式,很多⽂章都推荐使⽤entrySet,认为其⽐keySet的效率⾼很多.理由是:entrySet⽅法⼀次拿到所有key和
value的集合:⽽keySet拿到的 ...
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· 分享4款.NET开源、免费、实用的商城系统
· 解决跨域问题的这6种方案,真香!
· 5. Nginx 负载均衡配置案例(附有详细截图说明++)
· Windows 提权-UAC 绕过