Java8 forEach方法
精华
小牛编辑
131浏览
2023-03-14
1 Java8 forEach方法的介绍
Java提供了一个新的forEach() 方法来迭代元素。它在Iterable和Stream接口中定义。这是Iterable接口中定义的默认方法。扩展Iterable接口的集合类可以使用forEach循环来迭代元素。
此方法采用单个参数,该参数是功能接口。因此,您可以将lambda表达式作为参数传递。
2 Java8 forEach方法的声明
default void forEach(Consumer<super T>action)
3 Java8 forEach方法的案例1
/**
* 小牛知识库网: https://www.xnip.cn
*/
import java.util.ArrayList;
import java.util.List;
public class ForEachExample {
public static void main(String[] args) {
List<String> gamesList = new ArrayList<String>();
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
4 Java8 forEach方法的案例2
/**
* 小牛知识库网: https://www.xnip.cn
*/
import java.util.ArrayList;
import java.util.List;
public class ForEachExample {
public static void main(String[] args) {
List<String> gamesList = new ArrayList<String>();
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