Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the Lambda expression?

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces what the Lambda expression is, the content is very detailed, interested friends can refer to it, I hope it can be helpful to you.

1. Brief introduction to Lambda

You can think of an Lambda expression as a way to succinctly represent an anonymous function that can be passed: it doesn't have a name, but it has a parameter list, a function body, a return type, and maybe a list of exceptions that can be thrown.

Anonymity-We say anonymous because it doesn't have a clear name like a normal method: write less and think more!

Function-we say it is a function because the Lambda function does not belong to a particular class like a method. But like methods, Lambda has a list of parameters, a function body, a return type, and possibly a list of exceptions that can be thrown.

Pass-- Lambda expressions can be passed as parameters to methods or stored in variables.

Simplicity-you don't have to write a lot of template code like anonymous classes.

2. Lambda writing method

(parameters)-> expression or (parameters)-> {statements;} eg: (Apple A1, Apple a2)-> a1.getWeight (). CompareTo (a2.getWeight ()); the Lambda expression has three parts:

Parameter list-here it takes the parameters of the compare method in Comparator, two Apple.

Arrow-- Arrow-- separates the parameter list from the Lambda body.

Lambda body-compares the weight of two Apple. The expression is the return value of Lambda.

3. Functional interfaces and function descriptors

A functional interface is an interface that defines only one abstract method. The @ FunctionalInterface mark on the interface indicates that the interface will be designed as a functional interface. If you define an interface with @ FunctionalInterface, but it is not a functional interface, the compiler will return an error indicating the cause. Interfaces can now also have default methods (that is, when the class does not implement the method, its body provides the method with the default implementation for the method). Even if there are many default methods, as long as the interface defines only one abstract method, it is still a functional interface.

The signature of the abstract method of the functional interface is the signature of the Lambda expression. We call this abstract method: function descriptors. For example, the Runnable interface can be thought of as the signature of a function that accepts nothing and returns nothing (void), because it has only one abstract method called run, which accepts nothing and returns nothing (void).

4. Three commonly used functional interfaces 4.1 Predicate/** * Represents a predicate (boolean-valued function) of one argument. *

This is a functional interface * whose functional method is {@ link # test (Object)}. * @ param the type of the input to the predicate * @ since 1.8 * / @ FunctionalInterfacepublic interface Predicate {/ * Evaluates this predicate on the given argument. * @ param t the input argument * @ return {@ code true} if the input argument matches the predicate, * otherwise {@ code false} * / boolean test (T t);}

The English meaning of Predicate is: predicate. The Predicate interface defines an abstract method called test, which accepts a generic T object and returns a boolean.

4.2 Consumer/*** Represents an operation that accepts a single input argument and returns no* result. Unlike most other functional interfaces, {@ code Consumer} is expected* to operate via side-effects.*

This is a functional interface* whose functional method is {@ link # accept (Object)}. * @ param the type of the input to the operation* @ since 1.8*/@FunctionalInterfacepublic interface Consumer {/ * * Performs this operation on the given argument. * @ param t the input argument * / void accept (T t);}

The English sign of Consumer is: consumer. The Consumer interface defines an abstract method called accept, which accepts a generic T object and returns no value.

4.3 Function/*** Represents a function that accepts one argument and produces a result.*

This is a functional interface* whose functional method is {@ link # apply (Object). * @ param the type of the input to the function* @ param the type of the result of the function* @ since 1.8*/@FunctionalInterfacepublic interface Function {/ * Applies this function to the given argument. * @ param t the function argument * @ return the function result * / R apply (T t);}

The English meaning of Function is: function. The Function interface defines an abstract method called apply, which accepts a generic T object and returns an object of generic R.

Java also has an auto-boxing mechanism to help programmers perform this task: boxing and unpacking are done automatically. But this comes at a price in terms of performance. The boxed value essentially wraps the original type and stores it in the heap. Therefore, the boxed value requires more memory, and an additional memory search is required to get the original value that is wrapped. Java 8 brings a special version of the functional interface we mentioned earlier to avoid automatic boxing when the inputs and outputs are primitive types.

4.4 functional interfaces commonly used in Java 8

5. Type checking, type inference, and restriction 5.1 type checking

The type of Lambda is inferred from the context in which Lambda is used. The type required by the Lambda expression in the context (for example, accepting the parameters of the method it passes, or the local variable that accepts its value) is called the target type. The type checking process can be broken down as follows.

First, you need to find out the declaration of the filter method.

Second, it is required to be the second formal parameter of the Predicate (target type) object.

Third, Predicate is a functional interface that defines an abstract method called test.

Fourth, the test method describes a function descriptor that accepts an Apple and returns a boolean.

Finally, any actual parameters of the filter must match this requirement.

This code is valid because the Lambda expression we pass also takes Apple as a parameter and returns a boolean. Note that if the Lambda expression throws an exception, the throws statement declared by the abstract method must match it. With the concept of the target type, the same Lambda expression can be associated with different functional interfaces, as long as their abstract method signatures are compatible. For example, Callable and PrivilegedAction mentioned earlier, both interfaces represent functions that accept nothing and return a generic T. Therefore, the following two assignments are valid:

Callable c = ()-> 42 × PrivilegedAction p = ()-> 42

Special void compatibility rules if the body of a Lambda is a statement expression, it is compatible with a function descriptor that returns void (of course, the argument list is also compatible). For example, the following two lines are valid, although the add method of List returns a boolean instead of the void required by the Consumer context (T-> void):

/ / Predicate returned a boolean Predicate p = s-> list.add (s); / / Consumer returned a void Consumer b = s-> list.add (s); 5.2 type inference

The Java compiler infers from the context (the target type) what functional interface to use to match the Lambda expression, which means that it can also infer a signature that is appropriate for Lambda, because the function descriptor can be obtained from the target type. The advantage of this is that the compiler can know the parameter type of the Lambda expression, so you can omit the annotation parameter type in the Lambda syntax.

/ / No type inference Comparator c = (Apple A1, Apple a2)-> a1.getWeight (). CompareTo (a2.getWeight ()); / / typed inference Comparator c = (A1, a2)-> a1.getWeight (). CompareTo (a2.getWeight ())

Lambda expressions also allow the use of free variables (not parameters, but variables defined in the outer scope), just like anonymous classes. They are called capture Lambda. Local variables captured by Lambda must be explicitly declared as final, or in fact final. In other words, Lambda expressions can only capture the local variables assigned to them once.

First, there is a key difference between the implementation behind instance variables and local variables. Instance variables are stored in the heap, while local variables are stored on the stack. If Lambda has direct access to local variables and Lambda is used in a thread, threads that use Lambda may access the variable after the thread that assigned it takes it back. Therefore, when Java accesses a free local variable, it is actually accessing a copy of it, not the original variable. If a local variable is assigned only once, it makes no difference-- so there is this limitation.

Second, this limitation discourages you from using a typical imperative programming model that changes external variables (as we will explain in later chapters, this pattern hinders parallel processing that is easy to do).

6. Method reference

A method reference can be seen as a shortcut to a Lambda that only calls a particular method, and a method reference can be seen as a syntax sugar for a Lambda that only involves a single method. The target reference is placed before the delimiter::, and the name of the method is placed after it. There are three main types of method references:

(1) method references pointing to static methods (for example, Integer's parseInt method, writing Integer::parseInt).

(2) method references that point to any type of instance method (for example, String's length method, write String::length).

(3) the method reference to the instance method of the existing object (suppose you have a local variable expensiveTransaction for storing objects of type Transaction, which supports the instance method getValue, then you can write expensive- Transaction::getValue).

For an existing constructor, you can use its name and keyword new to create a reference to it: ClassName::new. It functions like a reference to a static method. Supplier C1 = Apple::new;Apple A1 = c1.get (); this is equivalent to: Supplier C1 = ()-> new Apple (); / / create Apple's Lambda expression Apple A1 = c1.get () with the default constructor; / / call Supplier's get method to produce a new Apple7. A useful method for compound Lambda expressions 7.1 comparator compound Comparator c = Comparator.comparing (Apple::getWeight); / / sort inventory.sort by decreasing weight in reverse order (comparing (Apple::getWeight). Reversed ()); / / the chain of comparators is sorted by decreasing weight; when two apples are the same weight, inventory.sort (comparing (Apple::getWeight). Ordered () .thencomparing (Apple::getCountry)) Verbs compound / / generate the non-Predicate notRedApple = redApple.negate () of the existing Predicate object redApple; / / Link two predicates to generate another Predicate object one apple is both red and heavy Predicate redAndHeavyApple = redApple.and (a-> a.getWeight () > 150) / / the method of linking Predicate to construct more complex Predicate object expressions is either a red apple weighing more than 150g or a green apple Predicate redAndHeavyAppleOrGreen = redApple.and (a-> a.getWeight () > 150g). Or (a-> "green" .equals (a.getColor () Note that the and and or methods determine priority from left to right based on their position in the chain of expressions. Therefore, a.or (b). And (c) can be thought of as (a | | b) & & c. The function compound andThen method returns a function that applies a given function to the input and then another function to the output. For example, Function f = x-> x + 1 × function g = x-> x * 2 × function h = f.andThen (g); int result = h.apply (1); mathematically write g (f (x)) or (g o f) (x), which returns the 4compose method, using the given function as the function given in the arguments to compose, and then using the function itself for the result. Function f = x-> x + 1x f o g function g = x-> x * 2X function h = f.compose (g); int result = h.apply (1); mathematically can write f (g (x)) or (f o g) (x), which returns 3

Here are the key concepts you should learn from this chapter.

An Lambda expression can be understood as an anonymous function: it has no name, but it has a list of arguments, a function body, a return type, and perhaps a list of exceptions that can be thrown.

Lambda expressions allow you to pass code succinctly.

A functional interface is an interface that simply declares an abstract method.

Lambda expressions can only be used where functional interfaces are accepted.

Lambda expressions allow you to inline directly, provide implementations for abstract methods of functional interfaces, and use the entire expression as an instance of a functional interface.

Java 8 comes with some commonly used functional interfaces, which are included in the java.util.function package, including Predicate, Function, Supplier, Consumer and BinaryOperator, as described in Table 3-2.

In order to avoid boxing operation, the primitive types of general functional interfaces such as Predicate and Function are specialized: IntPredicate, IntToLongFunction, etc.

Surround execution mode (that is, what you need to do in the middle of the code necessary for the method, such as resource allocation and cleanup) can work with Lambda to improve flexibility and reusability.

The type that the Lambda expression needs to represent is called the target type.

Method references let you reuse existing method implementations and pass them directly.

Functional interfaces such as Comparator, Predicate, and Function all have several default methods that can be used to combine Lambda expressions.

About what the Lambda expression is to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report