java
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
}
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
entries.next();
}
map.forEach((key, value) -> {
});
map.entrySet().stream().forEach((entry) -> {
});
map.entrySet().parallelStream().forEach((entry) -> {
});
java
for (Integer key : map.keySet()) {
}
Iterator<Integer> iteratorKeySet = map.keySet().iterator();
while (iteratorKeySet.hasNext()) {
iteratorKeySet.next();
}
map.keySet().forEach((key) -> {
});
map.keySet().stream().forEach((entry) -> {
});
map.keySet().parallelStream().forEach((entry) -> {
});
java
for (Integer value : map.values()) {
}
Iterator<Integer> iteratorValues = map.values().iterator();
while (iteratorValues.hasNext()) {
iteratorValues.next();
}
map.values().forEach((values) -> {
});
map.values().stream().forEach((entry) -> {
});
map.values().parallelStream().forEach((value) -> {
});
for (Integer key : map.keySet()) {
map.get(key);
}
性能比较
java
每种循环各遍历50000000次 total cost time = 3996 ms
map.entrySet() : 348 ms, 8.71%
map.entrySet().iterator() : 356 ms, 8.91%
map.forEach : 235 ms, 5.88%
map.entrySet().stream().forEach : 227 ms, 5.68%
map.entrySet().parallelStream().forEach : 116 ms, 2.90%
map.keySet() : 294 ms, 7.36%
map.keySet().iterator() : 301 ms, 7.53%
map.keySet().forEach : 226 ms, 5.66%
map.keySet().stream().forEach : 227 ms, 5.68%
map.keySet().parallelStream().forEach : 126 ms, 3.15%
map.values() : 301 ms, 7.53%
map.values().iterator() : 303 ms, 7.58%
map.values().forEach : 219 ms, 5.48%
map.values().stream().forEach : 228 ms, 5.71%
map.values().parallelStream().forEach : 122 ms, 3.05%
map.keySet() → map.get(key) : 358 ms, 8.96%