In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces "Java instance Analysis Lambda expression". In daily operation, I believe many people have doubts about Java example analysis of Lambda expression. Xiaobian consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts of "Java instance Analysis Lambda expression". Next, please follow the editor to study!
First acquaintance of Lambda
We know that in Java, an interface cannot be instantiated, but an interface object can point to its implementation class object. What if the interface doesn't even have an implementation object? You can also use anonymous classes, as follows:
Public class JavaTest {public static void main (String [] args) {Fly fly = new Fly () {@ Override public void fly (String name) {System.out.println (name + "flight");}}; fly.fly ("Zhang San");}} interface Fly {abstract void fly (String name);}
However, using the anonymous internal method, the code amount is not very concise, and in order to make the code more concise, Java introduces the Lambda expression to achieve this function through a simpler syntax. The simplified code using Lambda expression is as follows:
Public class JavaTest {public static void main (String [] args) {Fly fly = name-> System.out.println (name + "flight"); fly.fly ("Zhang San");} interface Fly {abstract void fly (String name);}
The same effect is achieved with Lambda expressions, but the amount of code is reduced quite right, and that's the beauty of Lambda expressions.
II. Functional interface
Before learning the syntax of Lambda expressions, you first need to know what a functional interface is. There is only one interface for a method to be implemented, which is called a functional interface.
/ / there is only one method fly in the interface to be implemented, so this is the functional interface interface Fly {void fly (String name);} / / there are two methods to be implemented in the interface. Is this the functional interface interface Run {void fastRun (); void slowRun () } / / there are two methods in the interface, but one of them is the defined default method. There is only one method that really needs to be implemented by the subclass. This is the functional interface interface Jump {void jump (); default void highJump () {System.out.println ("jump higher");}}
You can add a * * @ FunctionalInterface annotation to the interface to assert that the interface is a functional interface, and if the interface is not a functional interface, the compiler will prompt an error.
Why should I know what a functional interface is? Because Lambda expressions simplify the anonymous class implementation of an interface, it only works on functional interfaces.
It's easy to understand that if an interface has more than one method to implement, the Lambda expression cannot tell which method in the interface it is now implementing.
Third, Lambda expression syntax
Lambda expressions introduce an operator * * "- >" * * in the Java language, which is called the Lambda operator or arrowhead operator. It divides the Lambda into two parts:
Left: all parameters required by the Lambda expression are specified
Right: the Lambda body is defined, that is, the function to be performed by the Lambda expression.
Like this:
(parameters)-> expression or (parameters)-> {statements;}
Except for-> and Lambda body of Lambda expression, other parameters, parentheses and square brackets can be omitted from the parameter type and the number of lines of code in the method body.
Take the implementation of the following functional interface as an example:
Interface MathOperation {int operation (int a, int b);} interface GreetingService {void sayMessage (String message);} private int operate (int a, int b, MathOperation mathOperation) {return mathOperation.operation (a, b);} interface NoParam {int returnOne ();}
The following are important features of lambda expressions:
Optional type declaration: the Lambda expression does not have to declare the parameter type of the implementation method, and the compiler can uniformly identify the parameter values.
/ / Type declaration MathOperation addition = (int a, int b)-> a + b; / / No type declaration MathOperation subtraction = (a, b)-> a-b
Optional parameter parentheses: a parameter does not need to define parentheses, but no parameters or multiple parameters need to define parentheses.
/ do not use parentheses GreetingService greetService1 = message-> System.out.println ("Hello" + message); / / use parentheses GreetingService greetService2 = (message)-> System.out.println ("Hello" + message)
Optional curly braces: if the body contains a statement, you do not need to use braces.
/ / multiple statements cannot omit curly braces MathOperation multiplication = (int a, int b)-> {int num = axi1; num = a + b; return a * b + num;}; / / single statements can omit curly braces MathOperation pision = (int a, int b)-> a / b
Optional return keyword: if the body has only one expression return value, the compiler automatically returns a value, and curly braces need to specify that the expression returns a numeric value.
/ / if the Lambda expression of multiple statements has a return value, you need to use return MathOperation multiplication = (int a, int b)-> {int num = astat1; num = a + b; return a * b + num;}; / / A single statement can omit return MathOperation pision = (int a, int b)-> a / b; fourth, the scope of use of Lambda expression
Lambda expressions are not just used to simplify the creation of an anonymous class, it has more uses.
1. Assign values to variables
Above, the use of Lambda expressions is to assign values to variables, which simplifies the code snippet for anonymous inner class assignments and improves reading efficiency.
MathOperation subtraction = (a, b)-> a-b * * 2, as a result of return interface MathOperation {int operation (int a, int b);} MathOperation getOperation (int a, int b) {return (A1, b1)-> aqb } 3. As an array element MathOperation math [] = {(Arecom b)-> aquib, (amemb)-> arelb, 4. As a parameter public static void main (String args []) {Java8Tester java8Tester = new Java8Tester () as a common method or construction method. Java8Tester.operate (1Jue 2, ((a, b)-> aqb));} private int operate (int a, int b, MathOperation mathOperation) {return mathOperation.operation (a, b);} interface MathOperation {int operation (int a, int b);} V, scope of Lambda expression
Lambda expression is expressed in vivo, and variables outside the expression can be accessed, but other variables cannot be modified.
VI. Citation of Lambda expressions
When learning Lambda, you may also find a strange way to write it, such as the following code:
/ / method reference writing method GreetingService greetingService = System.out::println; greetingService.sayMessage ("hello world")
Here is a symbol that has never been seen before::, this is called a reference to a method.
Obviously, using method references is a little more concise than a normal Lambda expression.
If the implementation of a functional interface happens to be achieved by calling a method, then we can use a method reference.
Public class Java8Tester {public static void main (String args []) {/ / static method reference-call GreetingService greetingService = Test::MyNameStatic; greetingService.sayMessage ("hello") through the class name; Test t = new Test (); / / instance method reference-call GreetingService greetingService2 = t::myName through the instance / / Constructor method reference-No parameter Supplier supplier = Test::new; System.out.println (supplier.get ());} interface GreetingService {void sayMessage (String message);}} class Test {/ / static method public static void MyNameStatic (String name) {System.out.println (name) } / / instance method public void myName (String name) {System.out.println (name);} / / No-parameter construction method public Test () {}} 7, advantages and disadvantages of Lambda expression:
Fewer lines of code-one of the biggest benefits of lambda expressions is that they reduce the amount of code. We know that lambda expressions can only be used with functional interfaces. For example, Runnable is an interface, so we can easily apply lambda expressions.
Support sequential and parallel execution by passing the behavior as parameters in the method-passing functions to the collection method by using Stream API in Java 8. Now, the responsibility of the collection is to process the elements in a sequential or parallel manner.
Higher efficiency-by using Stream API and lambda expressions, you can achieve higher efficiency (parallel execution) in the case of batch manipulation of collections. In addition, lambda expressions help to implement internal iterations of the collection rather than external iterations.
Shortcoming
Running efficiency-without parallel computing, most of the time the computing speed is no faster than the traditional for cycle. (parallel computing sometimes needs to be preheated to show efficiency advantage)
It's hard to debug-Lambda expressions are hard to break and are not mode-friendly.
Not easy to understand-if other programmers have not learned lambda expressions, the code is not easy for programmers in other languages to understand (the reason I learn Lambda expressions is that I can't understand the Lambda expression code written by my colleagues)
At this point, the study of "Java instance analysis Lambda expression" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.