(argument1, argument2) -> expression |
() -> 3.14
|
double myMeth() { return 3.14;
}
|
() -> Math.random() * 10
|
// Demonstrate two simple lambda expressions.
//A functional interface. interface MyValue { double getValue(); } // Another functional interface. interface My Pa r amVa 1 ue { double getValue(double v); } Functional interfaces class LambdaDemo { public static void main(String args[]) { MyValue myVal; // declare an interface reference // Here, the lambda expression is simply a constant expression. // When it is assigned to myVal, a class instance is // constructed in which the lambda expression implements // the getValue() method in MyValue. myVal = () -> 98.6; ----------------------------A simple lambda expression // Call getValue(), which is provided by the previously assigned // lambda expression. System.out.printIn("A constant value: " + myVal.getValue()); // Now, create a parameterized lambda expression and assign it to // a MyParamValue reference. This lambda expression returns // the reciprocal of its argument. MyParamValue myPval = (n) -> 1.0 / n; <----------------A lambda expression that has a parameter // Call getValue(v) through the myPval reference. System.out.println("Reciprocal of 4 is " + myPval.getValue(4.0)); System.out.printin("Reciprocal of 8 is " + myPval.getValue(8.0)); // A lambda expression must be compatible with the method // defined by the functional interface. Therefore, these won't work: // myVal = () -> "three"; // Error! String not compatible with double! // myPval = () -> Math.random(); // Error! Parameter required! }}
|
A constant value: 98.6
Reciprocal of 4 is 0.25 Reciprocal of 8 is 0.125 |