In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the relevant knowledge of "how to use Java Lambda expression". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to use Java Lambda expression" can help you solve the problem.
I. background
Lambda expressions are an important new feature in Java SE 8. Lambda expressions allow you to replace functional interfaces with expressions. Lambda expressions, like methods, provide a normal list of parameters and a body (body, which can be an expression or a code) that uses these parameters
Block). The Lambda expression (Lambda expression) can be regarded as an anonymous function, which is named based on the λ calculus in mathematics. It can also be called Closure.
Syntax of 1.Lambda expressions
Basic syntax: (parameters)-> expression or (parameters)-> {statements;}
The Lambda expression consists of three parts:
1.paramaters: similar to the formal parameter list in a method, where the parameters are parameters in a functional interface. The parameter types here can be explicitly declared or undeclared and implicitly inferred by JVM. In addition, parentheses can be omitted when there is only one inferred type.
2.- >: can be understood as "to be used"
3. Method body: it can be an expression or a code block, which is the implementation of a method in a functional interface. The code block can return a value or nothing, where the code block is equivalent to the method body of the method. If it is an expression, you can also return a value or nothing.
/ / 1. No parameter is required, and the return value is 2 ()-> 2 prime / 2. Receives a parameter (numeric type) and returns twice its value x-> 2*x// 3. Take 2 parameters (numbers) and return their sum (xmemy)-> x+y// 4. Receives 2 int integers and returns their product (int x _ int y)-> x * y _ int / 5. Accept a string object and print it on the console without returning any value (which looks like returning void) (String s)-> System.out.print (s) 2. Functional interface
To understand Lambda expressions, you first need to understand what a functional interface is, a functional interface definition: an interface has one and only one abstract method.
Note:
1. If an interface has only one abstract method, then the interface is a functional interface
two。 If we declare the @ FunctionalInterface annotation on an interface, the compiler will require the interface according to the definition of the functional interface, so that if there are two abstract methods, the program will compile with an error. So, in a sense, you can omit this annotation as long as you ensure that there is only one abstract method in your interface. If you add it, it will be tested automatically.
How to define:
@ FunctionalInterfaceinterface NoParameterNoReturn {/ / Note: there can be only one abstract method void test ();}
But this approach is also possible:
@ FunctionalInterfaceinterface NoParameterNoReturn {void test (); default void test2 () {System.out.println ("New features of JDK1.8, default default method can have a specific implementation");}} II. Basic use of Lambda expressions
First, our implementation prepares several interfaces:
@ FunctionalInterfaceinterface NoParameterNoReturn {/ / Note: there can only be one abstract method void test ();} / / No return value one parameter @ FunctionalInterfaceinterface OneParameterNoReturn {void test (int a);} / No return value multiple parameters @ FunctionalInterfaceinterface MoreParameterNoReturn {void test (int a, int b);} / / return value and no parameter @ FunctionalInterfaceinterface NoParameterReturn {int test ();} / one parameter @ FunctionalInterfaceinterface OneParameterReturn {int test (int a) } / / return value multiple parameters @ FunctionalInterfaceinterface MoreParameterReturn {int test (int a, int b);}
As we mentioned above, the Lambda expression is essentially an anonymous function by returning the value method name argument list method body. In the Lambda expression, we only need to care about: the parameter list method body.
For specific use, please see the following sample code:
@ FunctionalInterfaceinterface NoParameterNoReturn {/ / Note: there can only be one abstract method void test ();} / / No return value one parameter @ FunctionalInterfaceinterface OneParameterNoReturn {void test (int a);} / No return value multiple parameters @ FunctionalInterfaceinterface MoreParameterNoReturn {void test (int a, int b);} / / return value and no parameter @ FunctionalInterfaceinterface NoParameterReturn {int test ();} / one parameter @ FunctionalInterfaceinterface OneParameterReturn {int test (int a) } / / return values multiple parameters @ FunctionalInterfaceinterface MoreParameterReturn {int test (int a, int b);} public class TestDemo2 {public static void main (String [] args) {NoParameterNoReturn noParameterNoReturn = ()-> {System.out.println ("No parameters and no return values");}; / / the body content of the test method is noParameterNoReturn.test () in the above parentheses OneParameterNoReturn oneParameterNoReturn = (int a)-> {System.out.println ("one return value without parameters:" + a);}; oneParameterNoReturn.test (10); MoreParameterNoReturn moreParameterNoReturn = (int a, int b)-> {System.out.println ("multiple parameters without return values:" + a + "" + b);}; moreParameterNoReturn.test (20,30) NoParameterReturn noParameterReturn = ()-> {System.out.println ("return values but no parameters!") ; return 40;}; / / the return value of the receiving function int ret = noParameterReturn.test (); System.out.println (ret); OneParameterReturn oneParameterReturn = (int a)-> {System.out.println ("return values and parameters!") ; return a;}; ret = oneParameterReturn.test (50); System.out.println (ret); MoreParameterReturn moreParameterReturn = (int a, int b)-> {System.out.println ("multiple parameters with return values!") ; return a + b;}; ret = moreParameterReturn.test (60,70); System.out.println (ret);}} III. Syntax simplification
Parameter types can be omitted, and if omitted, the type of each parameter is omitted.
If there is only one parameter in the parentheses, the parentheses can be omitted
If there is only one sentence of code in the method body, the curly braces can be omitted
If there is only one statement in the body of the method, which is the return statement, the curly braces can be omitted and the return keyword can be removed.
Sample code:
@ FunctionalInterfaceinterface NoParameterNoReturn {/ / Note: there can only be one abstract method void test ();} / / No return value one parameter @ FunctionalInterfaceinterface OneParameterNoReturn {void test (int a);} / No return value multiple parameters @ FunctionalInterfaceinterface MoreParameterNoReturn {void test (int a, int b);} / / return value and no parameter @ FunctionalInterfaceinterface NoParameterReturn {int test ();} / one parameter @ FunctionalInterfaceinterface OneParameterReturn {int test (int a) } / / return value multiple parameters @ FunctionalInterfaceinterface MoreParameterReturn {int test (int a, int b) } public class TestDemo2 {public static void main (String [] args) {/ / method parameters have more than one parameter and there is no return value in the method body, then the parameter type MoreParameterNoReturn moreParameterNoReturn = (a, b)-> {System.out.println ("no return value multiple parameters, parameter type:" + a + "" + b);}; moreParameterNoReturn.test (20,30) can be omitted. / / if there is only one parameter in the method, then the parentheses can omit OneParameterNoReturn oneParameterNoReturn = a-> {System.out.println ("there is only one parameter in the method, then the parentheses can be omitted:" + a);}; oneParameterNoReturn.test (10) / / No parameter, no return value. When there is only one line of code in the method body, you can remove the curly braces NoParameterNoReturn noParameterNoReturn = ()-> System.out.println ("No parameter, no return value, only one line of code in the method body"); noParameterNoReturn.test (); / / there is only one statement in the method body, and it is a return statement, and there is no parameter NoParameterReturn noParameterReturn = ()-> 40 Int ret = noParameterReturn.test (); System.out.println (ret);}} IV. Variable capture
There is a variable capture in the Lambda expression. After we understand the variable capture, we can better understand the scope of the Lambda expression. In the anonymous class in Java, there will be variable capture.
Next, we can also capture variables in Lambda. Let's take a look at the code:
@ FunctionalInterfaceinterface NoParameterNoReturn {void test ();} public class TestDemo2 {public static void main (String [] args) {int a = 10; NoParameterNoReturn noParameterNoReturn = ()-> {/ * Note that the value of a cannot be modified here, as in the anonymous inner class a = 99; * / System.out.println ("capture variable:" + a) }; noParameterNoReturn.test ();}} V. The use of Lambda in collections
In order to make the collection class set of Lambda and Java work better together, some interfaces have been added to the collection to interface with Lambda expressions.
The function of the above methods can be found in our help manual. We will demonstrate the use of some methods here. Note: the forEach () method of Collection is taken from the interface java.lang.Iterable.
1.Collection interface
Demonstration of the forEach () method
This method is in the interface Iterable. The prototype is as follows:
The * * forEach () * * method indicates that the action specified by action is performed on each element in the container
You can see that our parameter Consumer is actually a functional interface:
There is an abstract method accept in this functional interface:
Public class TestDemo2 {public static void main (String [] args) {ArrayList list = new ArrayList (); list.add ("Hello"); list.add ("bit"); list.add ("hello"); list.add ("lambda") List.forEach (new Consumer () {@ Override public void accept (String s) {/ / simply traverse the element System.out.println (s) in the collection;});}}
Output result:
Hello bit hello lambda
We can modify it to the following code:
Public class TestDemo2 {public static void main (String [] args) {ArrayList list = new ArrayList (); list.add ("Hello"); list.add ("bit"); list.add ("hello"); list.add ("lambda"); list.forEach ((String)-> {System.out.println (s);});}}
At the same time, the code can be simplified:
Public class TestDemo2 {public static void main (String [] args) {ArrayList list = new ArrayList (); list.add ("Hello"); list.add ("bit"); list.add ("hello"); list.add ("lambda"); list.forEach (s-> System.out.println (s));}} VI. Demonstration of 1.sort () method of List interface
Sort method source code: this method sorts container elements according to the comparison rules specified by c.
You can see that its parameter is Comparator. Let's click in and take a look: it's another functional interface.
There is an abstract method in this interface called the compare method:
Examples of use:
Public class TestDemo2 {public static void main (String [] args) {ArrayList list = new ArrayList (); list.add ("Hello"); list.add ("bit"); list.add ("hello"); list.add ("lambda") / * sort the strings in the list collection by length * / list.sort (new Comparator () {@ Override public int compare (String o1, String O2) {return o1.length ()-o2.length ();}}) / * output the sorted result * / list.forEach (s-> System.out.println (s));}}
The output is as follows:
Bit Hello hello lambda
Change to an lambda expression:
Public class TestDemo2 {public static void main (String [] args) {ArrayList list = new ArrayList (); list.add ("Hello"); list.add ("bit"); list.add ("hello"); list.add ("lambda") / * sort the strings in the list collection by length * / list.sort ((String o1, String o2)-> {return o1.length ()-o2.length ();}) / * output the sorted result: bit Hello hello lambda * / list.forEach (s-> System.out.println (s));}}
You can also simplify the code at this time:
Public class TestDemo2 {public static void main (String [] args) {ArrayList list = new ArrayList (); list.add ("Hello"); list.add ("bit"); list.add ("hello"); list.add ("lambda") / * sort the strings in the list collection by length * / list.sort ((o1, O2)-> o1.length ()-o2.length ()) / * output the sorted result: bit Hello hello lambda * / list.forEach (s-> System.out.println (s));}} VII. Map API
The forEach () method of HashMap:
There is an abstract method called the accept method in this functional interface:
Code example:
Public class TestDemo2 {public static void main (String [] args) {HashMap map = new HashMap (); map.put (1, "hello"); map.put (2, "bit"); map.put (3, "hello"); map.put (4, "lambda") Map.forEach (new BiConsumer () {@ Override public void accept (Integer integer, String s) {System.out.println (integer + "" + s);}});}}
Output result:
1 hello
2 bit
3 hello
4 lambda
The code after using the lambda expression:
Public class TestDemo2 {public static void main (String [] args) {HashMap map = new HashMap (); map.put (1, "hello"); map.put (2, "bit"); map.put (3, "hello"); map.put (4, "lambda") Map.forEach ((Integer integer, String s)-> {System.out.println (integer + "" + s);});}}
You can also continue to simplify the code:
Public class TestDemo2 {public static void main (String [] args) {HashMap map = new HashMap (); map.put (1, "hello"); map.put (2, "bit"); map.put (3, "hello"); map.put (4, "lambda") Map.forEach ((integer, s)-> System.out.println (integer + "" + s));}} that's all for "how to use Java Lambda expressions". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.