package test; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class Test10 { public static void main(String[] args) { Map<String, Dog> map = new HashMap<>(); for (int i = 0; i < 1000_000; i++) { map.put("dog" + i, new Dog(i, "dog" + i)); } long nanoTime = System.nanoTime(); test1(map); long nanoTime1 = System.nanoTime(); test2(map); long nanoTime2 = System.nanoTime(); test3(map); long nanoTime3 = System.nanoTime(); test4(map); long nanoTime4 = System.nanoTime(); System.out.println((nanoTime1 - nanoTime) / 1000000.0); System.out.println((nanoTime2 - nanoTime1) / 1000000.0); System.out.println((nanoTime3 - nanoTime2) / 1000000.0); System.out.println((nanoTime4 - nanoTime3) / 1000000.0); } public static void test1(Map<String, Dog> map) { Iterator<Map.Entry<String, Dog>> entries = map.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, Dog> entry = entries.next(); int code=entry.getKey().hashCode()+entry.getValue().hashCode(); } } public static void test2(Map<String, Dog> map) { for (Map.Entry<String, Dog> entry : map.entrySet()) { int code=entry.getKey().hashCode()+entry.getValue().hashCode(); } } public static void test3(Map<String, Dog> map) { for (String key : map.keySet()) { int code=key.hashCode()+map.get(key).hashCode(); } } public static void test4(Map<String, Dog> map) { map.forEach((key, value) -> { int code=key.hashCode()+value.hashCode(); }); } } View Code
结果如下:
java8的foreach依然不负众望,最快的是增强for循环。
+最终结论
普通(数量级10W以下,非并行)遍历一个集合(List、Set、Map)如果在意效率,不要使用java8的foreach,虽然它很方便很优雅
任何时候使用增强for循环是你不二的选择