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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:51:43  来源:igfitidea点击:

What is the equivalent lambda expression for System.out::println

javalambdajava-8method-reference

提问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::printlnwill evaluate System.outfirst, then create the equivalent of a lambda expression which capturesthe evaluated value. Usually, you would use
o->System.out.println(o)to achieve the same as the method reference, but this lambda expression will evaluate System.outeach time the method will be called.

方法引用System.out::printlnSystem.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));