Home > Java > javaTutorial > Block lambda expressions

Block lambda expressions

Susan Sarandon
Release: 2025-01-08 08:08:40
Original
842 people have browsed it

Expressões lambda de bloco

Expression body: It is the simplest lambda expression body type, composed of a single expression. The code to the right of the lambda operator is a single expression that is automatically returned.

Block body: Unlike the expression body, the block body allows multiple instructions. This expands the operations that can be done with lambdas, such as variable declarations, loops, if and switch statements. To return a value, you must explicitly use a return.

statement

Example of block body usage: A block lambda can be used to find the smallest positive factor of an integer, through a functional interface like NumericFunc, which takes an int and returns an int.

// A block lambda that finds the smallest positive factor
// of an int value.
interface NumericFunc {
int func(int n);
}
class BlockLambdaDemo {
public static void main(String args[])
{
// This block lambda returns the smallest positive factor of a value.
// A block lambda expression
NumericFunc smallestF = (n) -> {
int result = 1;
// Gets the absolute value of n.
n = n < 0? -n : n;
for(int i=2; i <= n/i; i )
if((n % i) == 0) {
result = i;
break;
}
return result;
};
System.out.println("Smallest factor of 12 is " smallestF.func(12));
System.out.println("Smallest factor of 11 is " smallestF.func(11));
}
}

Output:
Smallest factor of 12 is 2
Smallest factor of 11 is 1

The above is the detailed content of Block lambda expressions. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template