list遍历方法
List遍历方法
个人最常用的是增强for和stream流
-
简单for循环
List<Integer> list = Arrays.asList(1, 2, 3, 4); AtomicInteger sum3 = new AtomicInteger(); for (int i = 0; i < list.size(); i++) { sum += list.get(i); } System.out.println(sum);
-
增强for循环
List<Integer> list = Arrays.asList(1, 2, 3, 4); int sum = 0; for (Integer integer : list) { sum += integer; } System.out.println(sum);
-
迭代器
List<Integer> list = Arrays.asList(1, 2, 3, 4); int sum = 0; Iterator<Integer> iterator = list.iterator(); while (iterator.hasNext()) { sum += iterator.next(); } System.out.println(sum);
-
stream流
List<Integer> list = Arrays.asList(1, 2, 3, 4); int sum = 0; sum += list.stream().mapToInt(i -> i).sum(); System.out.println(sum);
-
foreach
注意foreach的参数为Lambda表达式,变量必须为final
List<Integer> list = Arrays.asList(1, 2, 3, 4); final int[] sum = {0}; list.forEach(i -> sum[0] +=i); System.out.println(sum[0]);
List<Integer> list = Arrays.asList(1, 2, 3, 4); AtomicInteger sum = new AtomicInteger(); list.forEach(sum::addAndGet); System.out.println(sum);
思考
- stream流,引申出java8新特性的知识点
- foreach,引申出Lambda表达式和方法引用以及原子类操作知识点