📜  Java8 forEach循环

📅  最后修改于: 2020-10-13 03:31:38             🧑  作者: Mango

Java forEach循环

Java提供了一个新的forEach()方法来迭代元素。它在Iterable和Stream接口中定义。这是Iterable接口中定义的默认方法。扩展Iterable接口的集合类可以使用forEach循环来迭代元素。

该方法采用单个参数,该参数是功能接口。因此,您可以将lambda表达式作为参数传递。

迭代接口中的forEach()Signature(签名)

default void forEach(Consumeraction)

Java 8 forEach()示例1

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

Java 8 forEach()示例2

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 Stream forEachOrdered()方法

Java与forEach()方法一起,为EachOrdered()提供了另一种方法。它用于按流指定的顺序迭代元素。

特质:

void forEachOrdered(Consumer action)

Java Stream forEachOrdered()方法示例

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