search
HomeJavajavaTutorialLambda expressions in action

As expressões lambda em ação

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 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 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 if(myTest.test(2, 10))
System.out.println("2 is less than 10");
//...
myTest = (n, m) -> (n 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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does platform independence benefit enterprise-level Java applications?How does platform independence benefit enterprise-level Java applications?May 03, 2025 am 12:23 AM

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?May 03, 2025 am 12:22 AM

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.May 03, 2025 am 12:21 AM

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

What are the benefits of Java's platform independence for developers?What are the benefits of Java's platform independence for developers?May 03, 2025 am 12:15 AM

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

What are the advantages of using Java for web applications that need to run on different servers?What are the advantages of using Java for web applications that need to run on different servers?May 03, 2025 am 12:13 AM

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment