Java 17 Recipes


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

 How It Works
A basic building block of a lambda expression is the functional interface. This standard 
Java interface contains a single abstract method declaration and provides a target type 
for lambda expressions and method references. A functional interface may contain 
default method implementations, but only one abstract declaration. The abstract 
method is then implicitly implemented by the lambda expression. As a result, the 
lambda expression can be assigned to a variable of the same type as the functional 
interface. The method can be called on from the assigned variable later, thus invoking 
the lambda expression. Following this pattern, lambda expressions are method 
implementations that can be invoked by name. They can also be passed as arguments to 
other methods.
At this point, you may be wondering if you are required to develop a functional 
interface for each situation that may be suitable for use with a lambda expression. This 
is not the case since many functional interfaces are already available for use. Some 
examples include java.lang.Runnable, javafx.event.EventHandlerEvent>, and java.util.Comparator. See some of the other recipes in this chapter 
for examples using lambda expressions that implement these interfaces. However, 
many more functional interfaces are less specific, enabling them to be tailored to suit 
the needs of a particular requirement. The java.util.function package contains 
several functional interfaces that can be useful when implementing lambda expressions. 
The functional interfaces contained within the package are utilized throughout the 
JDK and can also be utilized in developer applications. Utilizing functional interfaces 
contained within the java.util.function package can greatly reduce the amount of 
code you need to write. The functional interfaces are geared toward tasks performed 
ChapTer 6 LaMbda expressIons


214
a high percentage of the time. They are also written using generics, which can be 
applied in many different contexts. Solution 2 demonstrates such an example, whereby 
the Function interface implements a lambda expression that accepts a string 
argument and returns a string result.

Download 3.2 Mb.

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




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