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

An example Analysis of the Anonymous function lambda expression of java8

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Most people do not understand the knowledge points of this article "java8 Anonymous function lambda expression instance Analysis", so the editor summarizes the following, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "java8 Anonymous function lambda expression instance Analysis" article.

I. concept

In essence, it is an anonymous function that can be used to implement methods in the interface directly, thus simplifying the code. But Lambda has a limitation that it cannot implement all the methods in the interface, so Lambda expressions can only be used for one or only one method interface that must be implemented, and it is important to note that these six words must be implemented.

Public interface Printer {/ / has a method that needs to be implemented, you can use the Lambda expression void print ();} public interface Printer {/ / has a method that needs to be implemented, you can use the Lambda expression void print () / / although there is a method here, the interface provides a default implementation, so it is not necessary to implement default void printDetail () {}} public interface Printer {/ / there is a method that needs to be implemented, and the Lambda expression void print () can be used; / / although there is a method that needs to be implemented, it is not necessary because toString () is .String toString () in the Object class. } public interface Printer {/ / there is a method that needs to be implemented, and you can use the Lambda expression void print (); / / although there is a method that needs to be implemented, it is not necessary because toString () is the .String toString (); in the Object class.

An interface like this, which has only one method that must be implemented, is called a functional interface in java8. When defining an interface, you can add a @ FunctionInterface tag to the interface name to verify whether the interface is a functional interface. If the interface is not a functional interface after it is defined, an error will be reported at the interface name.

When using Lambda expressions, you don't need to care about the method name, just the method parameters and the return value. The basic syntax is simple:

(parameter list)-> {method body}; II. Usage comparison

There are two ways to implement an interface in java before java8: define the implementation class of the interface and use anonymous classes, but Lambda expressions are much simpler than this method. The Printer API described above is implemented as follows:

2.1 implementation class class PrinterImpl implements Printer {@ Override public void print () {System.out.println ("Hello World") Class PrinterAnonymous {Printer printer = new Printer () {@ Override public void print () {System.out.println ("Hello World");}} } 2.3 Lambdaclass PrinterLambda {Printer p = ()-> System.out.println ("Hello World");}

Comparing the above three implementations, it shows that the implementation of Lambda is much simpler than the first two.

3. Basic usage 3.1 No parameter no return value interface method @ FunctionalInterfacepublic interface Printer {void print ();} public class Tester {public static void main (String [] args) {/ / method 1, if there is no return value, the method body has only one statement. You can omit curly braces Printer p1 = ()-> System.out.println ("Hello World 1"). P1.print (); / / method 2, standard definition Printer p2 = ()-> {System.out.println ("Hello World 2");}; p2.print () }} 3.2 No return value for one parameter API method @ FunctionalInterfacepublic interface Printer {void print (String str) } public class Tester {public static void main (String [] args) {/ / method 1, if there is no return value, the method body has only one statement. Curly braces / / can be omitted because there is only one parameter, and parentheses can also be omitted. Parentheses are omitted on the premise that there is one and only one parameter / / Printer p1 = s-> System.out.println (s) Printer p1 = (s)-> System.out.println (s); p1.print ("Hello World 1"); / / method 2. If there is no return value, the method body has only one statement. You can omit the curly braces Printer p2 = (String s)-> System.out.println (s); p2.print ("Hello World 2"). / / method 3. Standard definition Printer p3 = (String s)-> {System.out.println (s);}; p3.print ("Hello World 3");}} 3.3.The API method with no return value for more than three parameters @ FunctionalInterfacepublic interface Printer {void print (String str1,String str2) } public class Tester {public static void main (String [] args) {/ / method 1, if there is no return value, there is only one statement in the method body. You can omit the curly braces / / reference Printer p1 = (s _ 1jue s _ 2)-> System.out.println (s _ 1 + "" + s _ 2); p1.print ("Hello World 1", "Java 1") / / method 2. If there is no return value, there is only one statement in the method body. You can omit the curly braces Printer p2 = (String S1 # string S2)-> System.out.println (S1 + "" + S2); p2.print ("Hello World 2", "Java 2"). / / method 3: standard definition Printer p3 = (String S1 and string S2)-> {System.out.println (S1 + "S2);}; p3.print (" Hello World 3 "," Java 3 ") @ FunctionalInterfacepublic interface Printer {boolean print ();} public class Tester {public static void main (String [] args) {/ / method 1, if there is a return value, there is only one statement. The presence or absence of the return keyword determines the vitality of the braces Printer p1 = ()-> true. Boolean has1 = p1.print (); System.out.println (has1); / / Test returns result / / method 2. Standard definition Printer p2 = ()-> {return true;}; boolean has2 = p2.print (); System.out.println (has2) / / Test results}} 3.5 A parameter has a return value API method @ FunctionalInterfacepublic interface Printer {boolean print (boolean good) } public class Tester {public static void main (String [] args) {/ / method 1, if there is a return value, there is only one statement. The existence of the return keyword determines whether the curly braces / / because there is only one parameter, and the parentheses can also be omitted. The premise that the parentheses are omitted is that there is only one parameter / / Printer p1 = good-> good. Printer p1 = (good)-> good; boolean has1 = p1.print (true); System.out.println (has1); / / method 2, standard definition Printer p2 = (good)-> {return good;}; boolean has2 = p2.print (false); System.out.println (has2) More than 3.6parameters have returned values. API method @ FunctionalInterfacepublic interface Printer {boolean print (boolean good1,boolean good2) } public class Tester {public static void main (String [] args) {/ / method 1, if there is a return value, there is only one statement, and the presence or absence of the return keyword determines whether the curly braces p1 = (good1,good2)-> good1; boolean has1 = p1.print (true,false); System.out.println (has1) / / method 2, standard definition Printer p2 = (good1,good2)-> {return good1;}; boolean has2 = p2.print (false,false); System.out.println (has2);}} IV. Function reference

When implementing a method of an interface, if a function somewhere else already implements the logic of the interface method, you can use the method reference to refer to the logic directly.

4.1 static method reference

Syntax:

Interface name variable name = class:: implemented method

Note:

Do not add parentheses after the referenced method

The referenced methods, parameters, and return values must be consistent with those defined in the interface

Example:

The method that Printer needs to implement has the same implementation in Checker, so it can be referenced directly.

@ FunctionalInterfacepublic interface Printer {String print (boolean good1,boolean good2);} public class Checker {public static String check (boolean a & & b) {return "Java is good";} else if (! a & & b) {return "Java is better" } return "Java is best";}} public class Tester {public static void main (String [] args) {Printer p1 = Checker::check;// uses the class name to reference System.out.println (p1.print (true, true));}} 4.2 non-static method reference

Syntax:

Interface name variable name = object:: static method

Note:

Do not add parentheses after the referenced method

The referenced methods, parameters, and return values must be consistent with those defined in the interface

Example:

The method that Printer needs to implement has the same implementation in Checker, so it can be referenced directly.

@ FunctionalInterfacepublic interface Printer {String print (boolean good1,boolean good2);} public class Checker {public String check (boolean a & & b) {return "Java is good";} else if (! a & & b) {return "Java is better" } return "Java is best";}} public class Tester {public static void main (String [] args) {Printer p1 = new Checker ():: check;// must refer to System.out.println (p1.print (true, true)) with an object;}} 4.3 reference to the constructor

If the method defined in a functional interface is simply to get an object, we can use a reference to the constructor to simplify the implementation of the method

Syntax:

Interface name variable name = class name:: new

Note:

You can distinguish between referencing different construction methods through the method parameters in the interface

Example:

@ FunctionalInterfacepublic interface Printer1 {Checker getCheck ();} @ FunctionalInterfacepublic interface Printer2 {Checker getCheck (int a);} public class Checker {int times; public Checker () {System.out.println ("I am none parameter");} public Checker (int a) {System.out.println ("I have one parameter") }} public class Tester {public static void main (String [] args) {/ / reference nonparametric construction method Printer1 p1 = Checker::new; p1.getCheck (); / / reference parametric construction method Printer2 p2 = Checker::new; p2.getCheck (1) } 4.4 Special references to object methods

If an object is included in the Lambda expression when implementing certain interfaces, the whole logic can be completed by directly using this object to call one of its methods in the method body. Other parameters can be used as parameters for calling methods. At this point, this implementation can be simplified.

Example:

@ FunctionalInterfacepublic interface Printer1 {int getCheck (Checker checker);} @ FunctionalInterfacepublic interface Printer2 {void setCheck (Checker checker, int a);} public class Tester {public static void main (String [] args) {Checker checker = new Checker (); checker.setTimes / / before simplification, use the lambda expression Printer1 p1 = x-> x.getTimes (); System.out.println (p1.getCheck (checker)); / / Test / / after simplification Printer1 p11 = Checker::getTimes; System.out.println (p11.getCheck (checker)) / / Test / / before simplification, use the lambda expression Printer2 p2 = (XMagne y)-> x.setTimes (y); p2.setCheck (checker, 50); System.out.println (checker.getTimes ()) as before / / Test / / simplified Printer2 p22 = Checker::setTimes; p22.setCheck (checker, 30); System.out.println (checker.getTimes ()); / / Test} 5. Note

When a local variable is used in a Lambda expression, the value of the local variable is outside the Lambda expression and cannot be changed because it is defined as a final constant by default. However, global variables have no such restrictions.

Example:

@ FunctionalInterfacepublic interface Printer {void setTime ();} public class Tester {public static void main (String [] args) {int time = 10; Printer p = ()-> System.out.println (time); / / there is an error here because the next line modifies time time = 15 time / the value here cannot be changed, which will cause an error on the previous line}}

Basically summed up all the uses of Lambda expression, shortcomings, please understand, thank you!

The above is about "java8 anonymous function lambda expression instance analysis" of this article, I believe we all have a certain understanding, I hope the editor to share the content to help you, if you want to know more related knowledge, please follow the industry information channel.

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: 295

*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

Development

Wechat

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

12
Report