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

JavaLambdaJava 8

Java Problem Overview


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

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?

Java Solutions


Solution 1 - Java

You have forgotten the generics on your 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)

Solution 2 - Java

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.

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 link has some additional examples that might help.

Solution 3 - Java

example of passing a lambda containing a method

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 "";
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsproketboyView Question on Stackoverflow
Solution 1 - JavaBoris the SpiderView Answer on Stackoverflow
Solution 2 - JavaJBCPView Answer on Stackoverflow
Solution 3 - JavaserupView Answer on Stackoverflow