在 Java 8 中如何将 lambda 赋值给变量?

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

How do you assign a lambda to a variable in Java 8?

javalambdajava-8

提问by sproketboy

Just playing with the new lambda and functional features in Java 8 and I'm not sure how to do this.

只是在 Java 8 中使用新的 lambda 和功能特性,我不知道如何做到这一点。

For example the following is valid:

例如以下是有效的:

    Map<String, Integer> map = new HashMap<>();
    map.put("A", 1);
    map.put("B", 2);
    map.put("C", 3);
    map.compute("A", (k, v) -> v == null ? 42 : v + 41));

but the following gives me syntax errors:

但以下给了我语法错误:

    BiFunction x = (k, v) -> v == null ? 42 : v + 41;
    map.compute("A", x);

Any ideas?

有任何想法吗?

采纳答案by Boris the Spider

You have forgotten the generics on your BiFunction:

你忘记了你的泛型BiFunction

public static void main(final String[] args) throws Exception {
    final Map<String, Integer> map = new HashMap<>();
    map.put("A", 1);
    map.put("B", 2);
    map.put("C", 3);
    final BiFunction<String, Integer, Integer> remapper = (k, v) -> v == null ? 42 : v + 41;
    map.compute("A", remapper);
}

Running:

跑步:

PS C:\Users\Boris> java -version
java version "1.8.0-ea"
Java(TM) SE Runtime Environment (build 1.8.0-ea-b120)
Java HotSpot(TM) 64-Bit Server VM (build 25.0-b62, mixed mode)

回答by JBCP

As Boris The Spider points out, the specific problem you have is the generics. Depending on context, adding an explicit {} block around the lambda will help add clarity and may be required.

正如 Boris The Spider 指出的那样,您遇到的具体问题是泛型。根据上下文,在 lambda 周围添加显式 {} 块将有助于增加清晰度并且可能是必需的。

With that, you would get something like:

有了这个,你会得到类似的东西:

BiFunction<String, Integer, Integer> x = (String k, Integer v) -> {v == null ? 42 : v + 41};

It would be pretty helpful for future readers who have the same problem if you posted your syntax errors so they can be indexed.

如果您发布语法错误以便将它们编入索引,这对于遇到相同问题的未来读者将非常有帮助。

This linkhas some additional examples that might help.

此链接有一些可能有帮助的其他示例。

回答by serup

example of passing a lambda containing a method

传递包含方法的 lambda 的示例

YourClass myObject = new YourClass();

// first parameter, second parameter and return 
BiFunction<String, YourClass, String> YourFunction; 

YourFunction = (k, v) -> v == null ? "ERROR your class object is null" : defaultHandler("hello",myObject);

public String defaultHandler(String message, YourClass Object)
{
     //TODO ...

     return "";
}