Some simple examples that put the basic concepts of lambda expressions into practice:
Example 1 - Comparison of implementation without and with lambda
No use of lambda:
MyValueSemLambda1 interface {
double getValue(); // Abstract method
}
class MyValueImpl implements MyValueSemLambda1{
private double value;
// Constructor to initialize the value
attribute
public MyValueImpl(double value) {
this.value = value;
}
// Implementation of the getValue method
@Override
public double getValue() {
return this.value;
}
}
public class MyValueSemLambda {
public static void main(String[] args) {
MyValueSemLambda1 myVal = new MyValueImpl(98.6); // Assigning value to the attribute
System.out.println("Value: " myVal.getValue()); // Prints 98.6
}
}
Using lambda:
MyValueCompare interface {
double getValue();
}
public class MyValueComparacao {
public static void main(String[] args) {
// Lambda expression without attribute, but returning a value
MyValueCompares myVal = () -> 98.6;
System.out.println("Value: " myVal.getValue()); // Prints 98.6
}
}
Example 2 - LambdaDemo
// A functional interface.
interface MyValue {
double getValue();
}
// Another functional interface.
interface MyParamValue {
double getValue(double v);
}
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, the instance
is constructed
// of a class where the lambda expression implements the
// getValue() method of MyValue.
myVal = () -> 98.6; A simple lambda expression
// Calls getValue(), which is provided by
// previously assigned lambda expression.
System.out.println("A constant value: " myVal.getValue());
// Now create a parameterized lambda expression and assign it
// for a MyParamValue reference. This lambda expression returns
// the reciprocal of its argument.
MyParamValue myPval = (n) -> 1.0/n; A lambda expression
which has a parameter
// Call getValue() via the myPval reference.
System.out.println("Reciprocal of 4 is " myPval.getValue(4.0));
System.out.println("Reciprocal of 8 is " myPval.getValue(8.0));
// A lambda expression must be compatible with the defined method
// through the functional interface. Therefore, these instructions will not work:
// myVal = () -> "three"; // Error! String is not compatible with double!
// myPval = () -> Math.random(); // Error! The parameter is required!
}
}
Output:
A constant value: 98.6
Reciprocal of 4 is 0.25
Reciprocal of 8 is 0.125
Example of incompatibilities:
A String value cannot be used if the expected return type is double.
A method that requires a parameter cannot be used without providing it.
A functional interface can be used with any compatible lambda expression.
Example 3 - NumericTest
Divisibility Test: Checks whether the first number is divisible by the second.
Size Comparison: Determines whether the first number is smaller than the second.
Comparison of Absolute Values: Returns true if the absolute values of the two numbers are equal.
// Functional interface that takes two parameters int and
// returns a boolean result.
interface NumericTest {
boolean test(int n, int m);
}
class LambdaDemo2 {
public static void main(String args[])
{
// This lambda expression determines whether a number
// is a factor of another.
NumericTest isFactor = (n, d) -> (n % d) == 0;
if(isFactor.test(10, 2))
System.out.println("2 is a factor of 10");
if(!isFactor.test(10, 3))
System.out.println("3 is not a factor of 10");
System.out.println();
// This lambda expression returns true if the
// first argument is smaller than the second.
NumericTest lessThan = (n, m) -> (n < m);
if(lessThan.test(2, 10))
System.out.println("2 is less than 10");
if(!lessThan.test(10, 2))
System.out.println("10 is not less than 2");
System.out.println();
// This lambda expression returns true if you
// absolute values of the arguments are equal.
NumericTest absEqual = (n, m) -> (n < 0 ? -n : n) == (m < 0 ? -m : m);
if(absEqual.test(4, -4))
System.out.println("Absolute values of 4 and -4 are equal.");
if(!lessThan.test(4, -5))
System.out.println("Absolute values of 4 and -5 are not equal.");
System.out.println();
}
}
Output:
2 is a factor of 10
3 is not a factor of 10
2 is less than 10
10 is not less than 2
Absolute values of 4 and -4 are equal.
Absolute values of 4 and -5 are not equal.
Compatible lambda expressions can be used with the same functional interface.
The same reference variable can be reused for different lambda expressions.
Reusing variables makes reading easier and saves resources in code.
In the example the same interface is used for different implementations:
NumericTest myTest;
myTest = (n, d) -> (n % d) == 0; //implementation 1
if(myTest.test(10, 2))
System.out.println("2 is a factor of 10");
// ...
myTest = (n, m) -> (n < m); //implementation 2
if(myTest.test(2, 10))
System.out.println("2 is less than 10");
//...
myTest = (n, m) -> (n < 0 ? -n : n) == (m < 0 ? -m : m); //implementation 3
if(myTest.test(4, -4))
System.out.println("Absolute values of 4 and -4 are equal.");
// ...
Clarity with reference variables
Using different reference variables (e.g. isFactor, lessThan, absEqual) helps you clearly identify which lambda expression each variable represents.
Multiple parameter specification
Multiple parameters in lambda expressions are separated by commas in a parenthetical list on the left side of the lambda operator.
Example: (n, d) -> (n % d) == 0.
Use of different types in lambda expressions
There is no restriction on the type of parameters or return in abstract methods of functional interfaces.
Non-primitive data types like String can be used in lambda expressions.
Example of testing with strings
A functional interface can be used to test specific string-related conditions, such as checking whether one string is contained within another.
// A functional interface that tests two strings.
interface StringTest {
boolean test(String aStr, String bStr);
}
class LambdaDemo3 {
public static void main(String args[])
{
// This lambda expression determines whether a string does
// part of another.
StringTest isIn = (a, b) -> a.indexOf(b) != -1;
String str = "This is a test";
System.out.println("Testing string: " str);
if(isIn.test(str, "is a"))
System.out.println("'is a' found.");
else
System.out.println("'is a' not found.");
if(isIn.test(str, "xyz"))
System.out.println("'xyz' Found");
else
System.out.println("'xyz' not found");
}
}
Output:
Testing string: This is a test
'is a' found.
'xyz' not found
StringTest functional interface
Defines an abstract method test(String aStr, String bStr) that returns a boolean value.
Implementation with lambda expression
The lambda expression (a, b) -> a.indexOf(b) != -1 checks if a string (b) is contained in another (a).
Type inference in parameters
Parameters a and b are inferred to be of type String, allowing the use of methods of the String class, such as indexOf.
The program tests the string "This is a test" to see if it contains the substrings "is a" and "xyz", printing the results accordingly.
The above is the detailed content of Lambda expressions in action. For more information, please follow other related articles on the PHP Chinese website!