System.out::println 的等效 lambda 表达式是什么 [英] What is the equivalent lambda expression for System.out::println

查看:30
本文介绍了System.out::println 的等效 lambda 表达式是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然发现了以下 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);
        }
    }
}

System.out::println 的等效 lambda 表达式是什么?

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 use
o -> 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆