本文概述
- 迭代接口中的forEach()签名
- Java Stream forEachOrdered()方法
该方法采用单个参数, 该参数是功能接口。因此, 你可以将lambda表达式作为参数传递。
迭代接口中的forEach()签名
default void forEach(Consumer<
super T>
action)
Java 8 forEach()示例1
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
Java 8 forEach()示例2
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
Java Stream forEachOrdered()方法Java与forEach()方法一起, 为EachOrdered()提供了另一种方法。它用于按流指定的顺序迭代元素。
Singnature:
void forEachOrdered(Consumer<
? super T>
action)
Java Stream forEachOrdered()方法示例
import java.util.ArrayList;
import java.util.List;
public class ForEachOrderedExample {
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.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
推荐阅读
- 用u盘安装win7系统推荐办法
- Java函数接口
- Java 8功能
- Java收集器
- Java 7 JDBC改进
- Java 7捕获多个异常
- Java泛型使用全解
- Java For-each循环|增强的For循环
- Java枚举用法详解