System.out :: println的等效lambda表达式是什么 [英] What is the equivalent lambda expression for System.out::println
问题描述
我偶然发现了以下Java代码,该代码使用的方法参考System.out.println
I stumbled upon the following Java code which is using a method reference for System.out.println
class SomeClass{
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9);
numbers.forEach(System.out::println);
}
}
}
什么是等效的lambda表达式for System.out :: println
?
What is the equivalent lambda expression for System.out::println
?
推荐答案
方法参考 System.out :: println
首先评估 System.out
,然后创建一个等同于的lambda表达式捕获评估值。通常,您将使用
o-> System.out.println(o)
来实现与方法引用相同的操作,但此lambda表达式将评估 System.out
每次调用该方法时。
The method reference System.out::println
will evaluate System.out
first, then create the equivalent of a lambda expression which captures the evaluated value. Usually, you would useo->System.out.println(o)
to achieve the same as the method reference, but this lambda expression will evaluate System.out
each time the method will be called.
所以完全等价物将是:
PrintStream p = Objects.requireNonNull(System.out);
numbers.forEach(o -> p.println(o));
如果有人调用 System.setOut(...),这会有所不同。
介于两者之间。
which will make a difference if someone invokes System.setOut(…);
in-between.
这篇关于System.out :: println的等效lambda表达式是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!