发布网友 发布时间:2024-09-25 18:15
共1个回答
热心网友 时间:2024-09-29 19:44
前言:有收获的话请加颗小星星,没有收获的话可以?反对 没有帮助 举报三连
8种有效方式1 iterator + Map.Entrylong i = 0;Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator();while (it.hasNext()) {Map.Entry<Integer, Integer> pair = it.next();i += pair.getKey() + pair.getValue();}System.out.println(i);2 foreach + Map.Entrylong i = 0;for (Map.Entry<Integer, Integer> pair : map.entrySet()) {i += pair.getKey() + pair.getValue();}System.out.println(i);3 foreach Java8final long[] i = {0};map.forEach((k, v) -> i[0] += k + v);System.out.println(i[0]);4 keySet + foreachlong i = 0;for (Integer key : map.keySet()) {i += key + map.get(key);}System.out.println(i);5 keySet + iteratorlong i = 0;Iterator<Integer> it = map.keySet().iterator();while (it.hasNext()) {Integer key = it.next();i += key + map.get(key);}System.out.println(i);6 for + Map.Entrylong i = 0;for (Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator(); entries.hasNext(); ) {Map.Entry<Integer, Integer> entry = entries.next();i += entry.getKey() + entry.getValue();}System.out.println(i);7 Java8 Stream ApiSystem.out.println(map.entrySet().stream().mapToLong(e -> e.getKey() + e.getValue()).sum());8 Java8 Stream Api parallelSystem.out.println(map.entrySet().parallelStream().mapToLong(e -> e.getKey() + e.getValue()).sum());效率对比# 初始化Mappublic final static Integer SIZE = 10000;public Map<Integer, Integer> map = toMap();public Map<Integer, Integer> toMap(){map = new HashMap<>(SIZE);for (int i = 0; i < SIZE; i++) {map.put(i, i);}return map;}SIZE = 10000SIZE = 1000000SIZE = 10000000总结通过数据对比,我们得知:
1 方式6是耗时最长的,方式8在数量少的时候耗时较长,但是数量大的时候耗时最短,因为方式8是并发执行。
2 一个有趣的现象,Test执行顺序总是for -> while -> foreach/stream,作者也没搞清楚为什么。
参考How do I efficiently iterate over each entry in a Java Map?
原文:https://juejin.cn/post/7103418770114215972