Java 通过 lambda 表达式调用 System.out.println()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23554413/
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-08-13 23:51:46  来源:igfitidea点击:

Calling System.out.println() through a lambda expression

javalambdajava-8

提问by λ Jonas Gorauskas

In C# I can write the following code:

在 C# 中,我可以编写以下代码:

public static Action<object> WL = x => Console.WriteLine(x);

... and then every time that I want to write something out to the console I just call:

...然后每次我想向控制台写一些东西时,我只需要调用:

WL("Some output");

What would be the equivalent code using Java 8 lambda expressions? I tried the following and it does not work:

使用 Java 8 lambda 表达式的等效代码是什么?我尝试了以下方法但它不起作用:

static void WL = (String s) -> { System.out.println(s); }

采纳答案by Jon Skeet

Your current attempt doesn't work because you're trying to declare a variable of type void- the equivalent would fail in C# too. You need to declare a variable of a suitable functional interface, just like you use a delegate type in C#.

您当前的尝试不起作用,因为您试图声明一个类型的变量void- 在 C# 中等效也会失败。您需要声明一个合适的函数式接口的变量,就像您在 C# 中使用委托类型一样。

You can do it with a lambda expression, but it would be cleaner (IMO) to use a method reference:

您可以使用 lambda 表达式来完成,但使用方法引用会更清晰(IMO):

import java.util.function.Consumer;

public class Test {
    public static void main(String[] args) {
        Consumer<Object> c1 = x -> System.out.println(x);
        Consumer<Object> c2 = System.out::println;

        c1.accept("Print via lambda");
        c2.accept("Print via method reference");
    }
}

Here the Consumer<T>interface is broadly equivalent to the Action<T>delegate in .NET.

这里的Consumer<T>接口大致相当于Action<T>.NET 中的委托。

Similarly you can use a method group conversion in C# rather than a lambda expression:

同样,您可以在 C# 中使用方法组转换而不是 lambda 表达式:

public static Action<object> WL = Console.WriteLine;

回答by Vince Emigh

interface MyMethod {
    public void print(String s);
}

class Main {
    public static void main(String[] args) {
        MyMethod method = (String s) -> { };
    }
}

In java, lambda expressions revolve around functional interfaces; interfaces only containing one method.

在java中,lambda表达式围绕着函数式接口;接口只包含一种方法。