java System.out::println 的等效 lambda 表达式是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28023364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the equivalent lambda expression for System.out::println
提问by Steve
I stumbled upon the following Java code which is using a method reference for System.out.println
我偶然发现了以下使用方法引用的 Java 代码 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);
}
}
}
What is the equivalent lambda expression for System.out::println
?
什么是等效的 lambda 表达式System.out::println
?
回答by Holger
The method reference System.out::println
will evaluate System.out
first, then create the equivalent of a lambda expression which capturesthe 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.
方法引用System.out::println
将System.out
首先求值,然后创建捕获求值值的 lambda 表达式的等效项。通常,您会使用o->System.out.println(o)
与方法引用相同的方法来实现,但是这个 lambda 表达式将在System.out
每次方法被调用时求值。
So an exactequivalent would be:
所以一个确切的等价物是:
PrintStream p = Objects.requireNonNull(System.out);
numbers.forEach(o -> p.println(o));
which will make a difference if someone invokes System.setOut(…);
in-between.
如果有人System.setOut(…);
在中间调用,这将有所作为。
回答by Eran
It's :
它的 :
numbers.forEach(i -> {System.out.println(i);});
or even simpler :
甚至更简单:
numbers.forEach(i -> System.out.println(i));