前言:有收获的话请加颗小星星,没有收获的话可以 反对 没有帮助 举报三连
8种有效方式
1 iterator + Map.Entry
long 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.Entry
long i = 0;for (Map.Entry<Integer, Integer> pair : map.entrySet()) { i += pair.getKey() + pair.getValue();}System.out.println(i);
3 foreach Java8
final long[] i = {0};map.forEach((k, v) -> i[0] += k + v);System.out.println(i[0]);
4 keySet + foreach
long i = 0;for (Integer key : map.keySet()) { i += key + map.get(key);}System.out.println(i);
5 keySet + iterator
long 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.Entry
long 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 Api
System.out.println(map.entrySet().stream().mapToLong(e -> e.getKey() + e.getValue()).sum());
8 Java8 Stream Api parallel
System.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 = 10000
SIZE = 1000000
SIZE = 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