public class MyTest {
    public static void  printValur(String str){
        System.out.println("print value : "+str);
    }
 
    public static void main(String[] args) {
        List<String> al = Arrays.asList("a""b""c""d");
        //下面面的forEach循环和上面的循环是等价的 
        for (String a: al) {
            MyTest.printValur(a);
        }
        //下面的for each循环和上面的循环是等价的 
        al.forEach(x->{
            MyTest.printValur(x);
        });
 
        al.forEach(AcceptMethod::printValur);
        //下面的方法和上面等价的
        Consumer<String> methodParam = MyTest::printValur; //方法参数
        al.forEach(x -> methodParam.accept(x));//方法执行accept
    }
}

  

  上面的所有方法执行玩的结果都是如下:

print value : a
print value : b
print value : c
print value : d

  在JDK8中,接口Iterable 8中默认实现了forEach方法,调用了 JDK8中增加的接口Consumer内的accept方法,执行传入的方法参数。

相关文章:

  • 2022-12-23
  • 2022-02-07
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-09-27
  • 2022-12-23
  • 2021-12-19
  • 2021-12-29
相关资源
相似解决方案