Java 17 Recipes


-2. Enabling the Use of Lambda Expressions


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

6-2. Enabling the Use of Lambda Expressions
 Problem
You are interested in authoring code that enables the use of lambda expressions.
 Solution 1
Write custom functional interfaces that can be implemented via lambda expressions. 
All lambda expressions implement a functional interface (i.e., a single abstract method 
declaration). The following lines of code demonstrate a functional interface that 
contains a single method declaration.
@FunctionalInterface
public interface ReverseType {
String reverse(String text);
}
ChapTer 6 LaMbda expressIons


212
The functional interface contains a single abstract method declaration, identified 
as String reverse(String text). The following code, which contains a lambda 
expression, demonstrates how to implement ReverseType.
ReverseType newText = (testText) -> {
String tempStr = "";
for (String part : testText.split(" ")) {
tempStr += new StringBuilder(part).reverse().toString() + " ";
}
return tempStr;
};
The following code could invoke the lambda expression.
System.out.println(newText.reverse("HELLO WORLD"));
This is the result.
OLLEH DLROW
 Solution 2
Use a functional interface that is contained within the java.util.function package to 
implement a lambda expression to suit the application’s needs. The following example 
uses Function (where T is the input type and R is the result type) interface to 
perform the same task as the one demonstrated in solution 1. This example accepts a 
string argument and returns a string result.
Function newText2 = (testText) -> {
String tempStr = "";
for (String part : testText.split(" ")) {
tempStr += new StringBuilder(part).reverse().toString() + " ";
}
return tempStr;
};
ChapTer 6 LaMbda expressIons


213
This lambda expression is assigned to the newText2 variable, which is of type 
Function. Therefore, a string is passed as an argument, and a string 
is returned from the lambda expression. The functional interface of Function 
contains an abstract method declaration of apply(). To invoke this lambda expression, 
use the following syntax.
System.out.println(newText2.apply("HELLO WORLD"));
The following is the result.
OLLEH DLROW

Download 3.2 Mb.

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




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