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
- The lambda expression must be compatible with the abstract method you implement.
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.
- In main(), three different tests are created using lambda expressions.
// 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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The difference between HashMap and Hashtable is mainly reflected in thread safety, null value support and performance. 1. In terms of thread safety, Hashtable is thread-safe, and its methods are mostly synchronous methods, while HashMap does not perform synchronization processing, which is not thread-safe; 2. In terms of null value support, HashMap allows one null key and multiple null values, while Hashtable does not allow null keys or values, otherwise a NullPointerException will be thrown; 3. In terms of performance, HashMap is more efficient because there is no synchronization mechanism, and Hashtable has a low locking performance for each operation. It is recommended to use ConcurrentHashMap instead.

Java uses wrapper classes because basic data types cannot directly participate in object-oriented operations, and object forms are often required in actual needs; 1. Collection classes can only store objects, such as Lists use automatic boxing to store numerical values; 2. Generics do not support basic types, and packaging classes must be used as type parameters; 3. Packaging classes can represent null values ??to distinguish unset or missing data; 4. Packaging classes provide practical methods such as string conversion to facilitate data parsing and processing, so in scenarios where these characteristics are needed, packaging classes are indispensable.

StaticmethodsininterfaceswereintroducedinJava8toallowutilityfunctionswithintheinterfaceitself.BeforeJava8,suchfunctionsrequiredseparatehelperclasses,leadingtodisorganizedcode.Now,staticmethodsprovidethreekeybenefits:1)theyenableutilitymethodsdirectly

The JIT compiler optimizes code through four methods: method inline, hot spot detection and compilation, type speculation and devirtualization, and redundant operation elimination. 1. Method inline reduces call overhead and inserts frequently called small methods directly into the call; 2. Hot spot detection and high-frequency code execution and centrally optimize it to save resources; 3. Type speculation collects runtime type information to achieve devirtualization calls, improving efficiency; 4. Redundant operations eliminate useless calculations and inspections based on operational data deletion, enhancing performance.

Instance initialization blocks are used in Java to run initialization logic when creating objects, which are executed before the constructor. It is suitable for scenarios where multiple constructors share initialization code, complex field initialization, or anonymous class initialization scenarios. Unlike static initialization blocks, it is executed every time it is instantiated, while static initialization blocks only run once when the class is loaded.

Factory mode is used to encapsulate object creation logic, making the code more flexible, easy to maintain, and loosely coupled. The core answer is: by centrally managing object creation logic, hiding implementation details, and supporting the creation of multiple related objects. The specific description is as follows: the factory mode handes object creation to a special factory class or method for processing, avoiding the use of newClass() directly; it is suitable for scenarios where multiple types of related objects are created, creation logic may change, and implementation details need to be hidden; for example, in the payment processor, Stripe, PayPal and other instances are created through factories; its implementation includes the object returned by the factory class based on input parameters, and all objects realize a common interface; common variants include simple factories, factory methods and abstract factories, which are suitable for different complexities.

InJava,thefinalkeywordpreventsavariable’svaluefrombeingchangedafterassignment,butitsbehaviordiffersforprimitivesandobjectreferences.Forprimitivevariables,finalmakesthevalueconstant,asinfinalintMAX_SPEED=100;wherereassignmentcausesanerror.Forobjectref

There are two types of conversion: implicit and explicit. 1. Implicit conversion occurs automatically, such as converting int to double; 2. Explicit conversion requires manual operation, such as using (int)myDouble. A case where type conversion is required includes processing user input, mathematical operations, or passing different types of values ??between functions. Issues that need to be noted are: turning floating-point numbers into integers will truncate the fractional part, turning large types into small types may lead to data loss, and some languages ??do not allow direct conversion of specific types. A proper understanding of language conversion rules helps avoid errors.
