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()); 复制代码
效率对比
# 初始化Map public 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,作者也没搞清楚为什么。