(parameters) -> { statements }
However, there are a number of variations and shortcuts for many cases.
int multiplyByTen(int x)
{
return x * 10;
}
The following is an equivalent lambda expression:
(int x) -> { return x * 10; }
Note that the compiler infers things from the context, including the return type
(int) in this case, because the incoming parameter is an integer.
(x) -> { return x * 10; }
(x) -> x * 10
x -> x * 10
() -> System.out.print("No params!")
| Function | equivalent lambda |
|---|---|
void PrintHello()
{
System.out.println("Hello, World");
}
|
() -> System.out.println("Hello, World")
|
double average(double x, double y, double z)
{
return (x + y + z) / 3.0;
}
|
(double x, double y, double z) -> (x + y + z) / 3.0(or, if used in appropriate context): (x, y, z) -> (x + y + z) / 3.0 |
void updateIfOdd(int x)
{
if (x % 2 != 0)
y = 10;
System.out.print("y is now " + y);
}
|
x -> { if (x % 2 != 0)
y = 10;
System.out.print("y is now " + y);
}
|
Since a lambda expression represents exactly one method (anonymous, without name), it is an ideal shortcut expression that can be used when creating the one method for such an interface parameter.
This version of the sorting program is similar to the "anonymous inner class" version, but uses lambda expressions instead, for simpler parameter syntax in the Arrays.sort() method calls.
For example, lengthier anonymous inner class notation like this:Arrays.sort(nameArray, new Comparatorhas been simplified with a lambda expression to this:() { public int compare(String s1, String s2) { return (s1.length() - s2.length()); } });
Arrays.sort(nameArray, (s1, s2) -> s1.length() - s2.length() );In library methods that take a functional interface type as a parameter, a lambda expression will typically be a syntactically simpler way to pass in an object that implements the given interface and defines the single method required. In these cases, we don't even need to worry about the method's name, becuase there is only ONE required method to override in a functional interface!
Try rewriting some previously-seen examples that used anonymous inner classes (from our GUI/event-handling examples) with lambda expressions.