Java 17 Recipes


-1. Writing a Simple Lambda Expression


Download 3.2 Mb.
Pdf ko'rish
bet113/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   109   110   111   112   113   114   115   116   ...   245
Bog'liq
Java 17 Recipes

6-1. Writing a Simple Lambda Expression
 Problem
You want to encapsulate functionality that prints a simple message.
 Solution
Write a lambda expression that accepts a single parameter that contains the message 
you want to print, and implement the printing functionality within the lambda. In the 
following example, a functional interface, HelloType, is implemented via a lambda 
expression and assigned to the helloLambda variable. Lastly, the lambda is invoked, 
printing the message.
public class HelloLambda {
/**
* Functional Interface
*/
@FunctionalInterface
public interface HelloType {
/**
* Function that will be implemented within the lambda
* @param text
*/
void hello(String text);
}
public static void main(String[] args){
// Create the lambda, passing a parameter named "text" to the
// hello() method, returning the string. The lambda is assigned
// to the helloLambda variable.
HelloType helloLambda =
(String text) -> {System.out.println("Hello " + text);};
// Invoke the method call
helloLambda.hello("Lambda");
}
}
ChapTer 6 LaMbda expressIons


209
The following is the result.
Hello Lambda
 How It Works
A lambda expression is an anonymous block of code that encapsulates an expression 
or a series of statements and returns a result. Lambda expressions are also known as 
closures in some other languages. They can accept zero or more parameters, which can 
be passed with or without type specification since the type can be automatically derived 
from the context.
The syntax of a lambda expression includes an argument list, a new character to the 
language known as the “arrow token” (->), and a body. The following model represents 
the structure of a lambda expression.
(argument list) -> { body }
The argument list for a lambda expression can include zero or more arguments. If 
there are no arguments, then an empty set of parentheses can be used. If there is only 
one argument, then no parentheses are required. Each argument on the list can include 
an optional type specification. If the type of the argument is left off, then the type is 
derived from the current context.
In the solution for this recipe, curly braces surround the body of a block, which 
contains more than a single expression. The curly braces are not necessary if the body 
consists of a single expression. The curly braces in the solution could have been left off, 
but they’ve been included for ease of readability. The body is simply evaluated and then 
returned. If the body of the lambda is an expression and not a statement, a return is 
implicit. On the contrary, if the body includes more than one statement, a return must 
be specified, and it marks a return of control back to the caller.
The following code demonstrates a lambda expression that does not contain any 
arguments.
StringReturn msg = () -> "This is a test";
The StringReturn interface, which is used by the lambda, is also known as a 
functional interface.
ChapTer 6 LaMbda expressIons


210
/**
* Functional interface returning a string
*/
@FunctionalInterface
public interface StringReturn {
String returnMessage();
}
Let’s take a look at how this lambda expression works. In the previous listing, an 
object of type StringReturn is returned from the lambda expression. The empty set 
of parentheses denotes that there are no arguments being passed to the expression. 
The return is implicit, and the string "This is a test" is returned from the lambda 
expression to the invoker. The expression in the example is assigned to a variable 
identified by msg. Assume that the functional interface, StringReturn, contains an 
abstract method identified as returnMessage(), as seen in the code. In this case, the 
msg.returnMessage() method can be invoked to return the string.
The body of a lambda expression can contain any Java construct that an ordinary 
method may contain. For instance, suppose a string was passed as an argument to a 
lambda expression, and you wanted to return some value that is dependent on the 
string argument. The following lambda expression body contains a block of code, which 
returns an int, based on the string value of the argument passed into the expression.
ActionCode code = (codestr) -> {
switch(codestr){
case "ACTIVE": return 0;
case "INACTIVE": return 1;
default:
return -1;
}
};
In this example, the ActionCode functional interface infers the return type of the 
lambda expression. For clarification, let’s see what the interface looks like.
@FunctionalInterface
public interface ActionCode{
int returnCode(String codestr);
}
ChapTer 6 LaMbda expressIons


211
The code implies that the lambda expression implements the returnCode method, 
which is defined within the ActionCode interface. This method accepts a string argument 
(codestr), which is passed to the lambda expression, returning an int. Therefore, 
from this example, you can see that a lambda can encapsulate the functionality of a 
method body.
While it is possible for code written in the Java language to move forward without the 
use of lambda expressions, they are an important addition that greatly improves overall 
maintainability, readability, and developer productivity. Lambda expressions are an 
evolutionary change to the Java language, as they are another step toward modernization 
of the language and help keep it in sync with other languages.
Note a lambda expression can contain any statement that an ordinary Java 
method contains. however, the continue and break keywords are not legal 
within the body of a lambda expression.

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   109   110   111   112   113   114   115   116   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling