current position:Home>15. & nbsp; Re learning java -- lambda expression

15. & nbsp; Re learning java -- lambda expression

2022-01-26 23:56:45 InfoQ

One 、Lambda expression

 Lambda Allows you to take a function as an argument to a method ( Function is passed into the method as an argument ),Lambda Expression is JavaSE8 It's an important new feature in .lambda Expressions allow you to replace functional interfaces with expressions .lambda Expressions are just like methods , It provides a normal list of parameters and a body that uses those parameters (body, It can be an expression or a block of code ).
Lambda Expressions also enhance the collection library .JavaSE8 Added 2 A package for batch operation of set data : java.util.function  Packages and  package . flow (stream) It's like an iterator (iterator), But there are a lot of extra features . in general ,lambda Expression and stream Is from Java Language add generics (Generics) Annotation (annotation) The biggest change since .
Use Lambda Expression can make the code more concise and compact .

Two 、 Important features

  • l Type declaration : Parameter types do not need to be declared , Compiler can identify parameter values uniformly .
  • Parameter parentheses : A parameter does not need to define parentheses , But multiple parameters need to define parentheses .
  • Curly braces : If the body contains a statement , You don't need braces .
  • Return keyword : If the body has only one expression return value, the compiler returns the value automatically , Braces need to specify that the expression returns a number .

3、 ... and 、 Access variables

 Lambda Expressions can access variables defined within their outer scope , Include : Member variables and local variables .

3.1 Member variables

  Member variables and static member variables . stay Lambda These member variables can be accessed in the expression , At this time  Lambda Expressions are the same as normal methods , You can read member variables , You can also modify member variables .

3.2 local variable

  Access to member variables Lambda Expressions are no different from ordinary methods , But for accessing outer local variables , It's going to happen “ To catch   Acquired variable ” situation .Lambda When capturing variables in expressions , Will treat variables as final Of , stay Lambda The captured variables cannot be modified in the expression

copyright notice
author[InfoQ],Please bring the original link to reprint, thank you.

Random recommended