在Java中如何使用forEach()迭代集合的内容?
Lambda表达式是函数接口的函数描述符的匿名表示。众所周知,所有的集合接口,如List、Set和Queue都使用Iterable作为它们的超级接口。从Java8开始,Iterable接口引入了一个名为forEach()的新方法。此方法对Iterable的内容按迭代时发生的顺序元素执行操作,直到处理完所有元素为止。
语法
void forEach(Consumer<? Super T> action)
在下面的程序中,我们可以使用forEach()方法迭代列表的内容,并使用lambda表达式和静态方法引用来打印内容。
示例
import java.util.*;
import java.util.function.*;
public class LambdaMethodRefIterationTest {
public static void main(String[] args) {
List<String> countries = Arrays.asList("India", "Australia", "England", "Newzealand", "Scotland");
System.out.println("==== 通过传递Lambda表达式进行迭代 ====");
countries.forEach(s -> System.out.println(s));
System.out.println("\n==== 通过传递静态方法引用进行迭代 ====");
countries.forEach(System.out::println);
System.out.println("\n==== 通过传递静态方法引用进行迭代 ====");
countries.forEach(Country::countWord);
}
}
class Country {
static void countWord(String s) {
System.out.println(s.length());
}
}输出结果
==== 通过传递Lambda表达式进行迭代 ====India Australia England Newzealand Scotland==== 通过传递静态方法引用进行迭代 ====India Australia England Newzealand Scotland==== 通过传递静态方法引用进行迭代 ====5 9 7 10 8
热门推荐
10 祝孙辈生日祝福语简短
11 恋人跨年祝福语大全简短
12 考大学敬酒简短祝福语
13 开工投产大吉祝福语 简短
14 偶然结婚祝福语朋友简短
15 感谢学长学姐祝福语简短
16 戏精的祝福语简短
17 我要结婚祝福语简短
18 婚前女儿生日祝福语简短