📅  最后修改于: 2020-10-13 03:31:38             🧑  作者: Mango
Java提供了一个新的forEach()方法来迭代元素。它在Iterable和Stream接口中定义。这是Iterable接口中定义的默认方法。扩展Iterable接口的集合类可以使用forEach循环来迭代元素。
该方法采用单个参数,该参数是功能接口。因此,您可以将lambda表达式作为参数传递。
default void forEach(Consumeraction)
import java.util.ArrayList;
import java.util.List;
public class ForEachExample {
public static void main(String[] args) {
List gamesList = new ArrayList();
gamesList.add("Football");
gamesList.add("Cricket");
gamesList.add("Chess");
gamesList.add("Hocky");
System.out.println("------------Iterating by passing lambda expression--------------");
gamesList.forEach(games -> System.out.println(games));
}
}
输出:
------------Iterating by passing lambda expression--------------
Football
Cricket
Chess
Hocky
import java.util.ArrayList;
import java.util.List;
public class ForEachExample {
public static void main(String[] args) {
List gamesList = new ArrayList();
gamesList.add("Football");
gamesList.add("Cricket");
gamesList.add("Chess");
gamesList.add("Hocky");
System.out.println("------------Iterating by passing method reference---------------");
gamesList.forEach(System.out::println);
}
}
输出:
------------Iterating by passing method reference---------------
Football
Cricket
Chess
Hocky
Java与forEach()方法一起,为EachOrdered()提供了另一种方法。它用于按流指定的顺序迭代元素。
void forEachOrdered(Consumer super T> action)
import java.util.ArrayList;
import java.util.List;
public class ForEachOrderedExample {
public static void main(String[] args) {
List gamesList = new ArrayList();
gamesList.add("Football");
gamesList.add("Cricket");
gamesList.add("Chess");
gamesList.add("Hocky");
System.out.println("------------Iterating by passing lambda expression---------------");
gamesList.stream().forEachOrdered(games -> System.out.println(games));
System.out.println("------------Iterating by passing method reference---------------");
gamesList.stream().forEachOrdered(System.out::println);
}
}
输出:
------------Iterating by passing lambda expression---------------
Football
Cricket
Chess
Hocky
------------Iterating by passing method reference---------------
Football
Cricket
Chess
Hocky