for 循环
迭代器 Iterator
- default void forEach(Consumer super T> action) {
- Objects.requireNonNull(action);
- for (T t : this) {
- action.accept(t);
- }
- }
不能修改forEach()外部变量值,会报错
return 不能停止 foreach
break,continue 会报错
- public static void main(String[] args) {
- List
list = Arrays.asList(new User(1, "陆小凤", "123456"), - new User(2, "西门吹雪", "123456"),
- new User(3, "叶孤城", "123456"));
- System.out.println("【方式一】obj->");
- list.forEach(obj-> System.out.println(obj));
-
- System.out.println("【方式二】System.out::println");
- list.forEach(System.out::println);
-
- System.out.println("【注意一】return 不能停止foreach");
- list.forEach(obj->{
- System.out.println(obj.getName());
- if (obj.getName().equals("西门吹雪")){
- System.out.println("return 不能停止foreach");
- return;
- }
-
- });
- System.out.println("【注意二】break,continue 会报错");
- }