Lambda expressions are anonymous functions. They have been introduced in Java 8 to represent functional interfaces. A functional interface is an interface with a single abstract method.
Three parts are required:
functional interface = arguments -> lambda expression
Here are some examples.
1) A simple lambda expression, represented by a native functional interface with an abstract method, without arguments:
Runnable runnable = () -> System.out.println("Hello");
2) Here's an example with a custom interface:
public interface Doable { void doIt(String s); }
The expression is assigned with one parameter:
Doable doable = (String s) -> System.out.println(s);
You can then call the implementation of the interface, passing the expected parameter:
doable.doIt("Hello");
3) Here is an other example with the above interface, but this time the functional interface is a method argument.
public void myMethod(Doable a) { a.doIt("Hello"); }
The method is called in that way:
myMethod((String s) -> System.out.println(s));
4) Most of the time you don't even need to write your own functional interface, because Java 8 provides the package java.util.function with some general-use interfaces, using generics. Here is an example with the interface Consumer:
public void myMethod(Consumer<String> a) { a.accept("Hello"); }
The method is called in that way:
myMethod((String sd) -> System.out.println(sd));
Copyright © 2013 Welcome to the website of Davis Fiore. All Rights Reserved.