在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