forEach() 源码:(java.lang.Iterable接口在 java8 新增的方法)
复制代码
1
2
3
4
5
6
7
8
9
10
11// 传入一个Consumer消费型函数式接口参数 default void forEach(Consumer<? super T> action) { // 对 对象进行非空判断 Objects.requireNonNull(action); // 循环执行 Consumer 接口的accept()方法 for (T t : this) { // 这个 this 是指调用 forEach() 方法的集合对象 action.accept(t); } }
注意( 面试可能会问哦 ):forEach方法的参数是一个Consumer消费型的函数式接口,接收一个参数,不返回结果。
forEach 的三种遍历方式:
-
直接使用 forEach 遍历
复制代码1
2
3
4
5
6
7// 将数组变成一个列表集合 List<Integer> list = Arrays.asList(1, 3, 5, 7, 9); // 遍历集合元素 for(int i : list) { System.out.println(i); }
-
使用 System.out::println
复制代码1
2
3
4
5// 将数组变成一个列表集合 List<Integer> list = Arrays.asList(1, 3, 5, 7, 9); // 遍历集合元素 list.forEach(System.out::println);
-
map集合,有键值对的情况下
复制代码1
2
3
4
5
6
7Map<String, String> map = new HashMap<>(); map.put("1", "11"); map.put("2", "22"); map.put("3", "33"); Set<String> set = map.keySet(); set.forEach((key) -> {System.out.println(key + " : " + map.get(key));});
最后
以上就是心灵美雪碧最近收集整理的关于forEach方法 ( Java 8新特性 )的全部内容,更多相关forEach方法内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复