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 > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "the usage of lambda expression in Java8". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "the usage of lambda expression in Java8".
Functional interface
Interfaces that contain only one abstract method are called functional interfaces, such as Runnable, Comparator, EventHandler. You can use lambda expressions to create instance objects of functional interfaces, such as:
Runnable task = ()-> System.out.println ("Hello Lambda!"); Comparator comp = (first, second)-> Integer.compare (first.length (), second.length ()); EventHandler handler = event-> System.out.println ("Thanks for clicking!")
Functional interfaces in Java usually annotate interface types using @ FunctionalInterface.
The role of Java lambda
The broad definition of an lambda expression is: an expression with parameters.
In Java, the only function of lambda expression is the transformation of functional interface. The lambda expression we write is to replace the implementation of functional interface and simplify the coding work.
The parameter list of the lambda expression corresponds to the parameter list of the abstract method of the functional interface, and the content of the lambda expression corresponds to the method body of the abstract method implementation.
Java lambda grammar (Type1 parameter1, Type2 parameter2,..., TypeN parameterN)-> {statement1; statement2;... StatementN; return value;}; example: (String first, String second)-> Integer.compare (first.length (), second.length ()); Simplification and deformation
If the lambda expression has no arguments, just write a pair of parentheses (), leaving a blank inside the parentheses
If the parameter type of an lambda expression can be deduced, the parameter type can be omitted; for example:
Comparator comp = (first, second)-> Integer.compare (first.length (), second.length ())
If an lambda expression has only one parameter, and the type of the parameter can be deduced, you can omit the parameter type and parentheses, for example:
EventHandler handler = event-> System.out.println ("Thanks for clicking!")
Supplement
The parameter list of lambda expression itself maps the parameter list of abstract methods of functional interface, so we can treat lambda expression parameters like method parameters, such as adding final modification, adding @ NonNull annotation, etc.
To make it easier to understand lambda, it is best to think of the lambda expression as a function rather than an object, and remember that the function can be converted into a functional interface equivalent
Method reference background
There is already a ready-made implementation of the operation you want to pass to other code, and you want to reuse the existing implementation, such as:
Button.setOnAction (event-> System.out.println (event)); can be simplified to:
Button.setOnAction (System.out::println)
The System.out::println is a method reference. Note that the method reference is equivalent to a lambda expression and also needs to be converted to a corresponding functional interface. To give another example, sort strings without case sensitivity:
Arrays.sort (strings, String::compareToIgnoreCase)
Three methods of citation
Class name:: static method name, reference to static method
Class name:: member method name, a reference to the member method of the object specified in the first parameter
Object:: member method name, reference to the specified object member method
Examples are as follows:
Example 1: (double x, double n)-> Math::pow
Example 2:Arrays.sort (strings, String::compareToIgnoreCase)
Example 3:button.setOnAction (System.out::println)
Examples of other common ways:
This:: instance method
Super:: instance method.
Constructor reference
Format: class name:: new, example:
Button::new, int []:: new (equivalent to x-> new int [x])
If there are multiple constructors, the compiler infers and selects the most appropriate constructor.
Constructor references can be used to break the limitation that Java cannot build generic arrays:
List lables =...; Stream stream = lables.stream (). Map (Button::new); Button [] buttons = stream.toArray (Button []:: new); variable scope public static void repeatMessage (String text, int count) {Runnable r = ()-> {for (int item0; I < count; iTunes +) {System.out.println (text); Thread.yield () } new Thread (r) .start ()
An lambda expression has three parts:
A piece of code
Parameters.
The value of a free variable, that is, a variable that is not a parameter and is not defined in the code, such as: text, count in the example above
Because the lambda expression may be executed after the repeatMessage method returns, the value of the free variable needs to be captured and saved when the method is called in order to use the variable value when the expression is executed
Blocks of code that contain free variables are called closures, so lambda expressions are closures of Java, and inner classes are also closures.
In the lambda expression, the value of the referenced external variable cannot be modified in the expression because it is not thread-safe. However, this immutable constraint is only used on the variable reference and cannot limit the modification of the value inside the variable, such as array elements, collection elements, or attributes of other instance variables.
Using this in a lambda expression refers to the object where the method of creating the lambda expression is located, rather than the this of the functional interface implementation class corresponding to the lambda expression
Variable definitions with the same name as local variables are not allowed in lambda expressions.
Default method background of the interface
In order to enable the inventory interface to support lambda expressions without affecting existing implementation classes, Java8 begins to support the default method implementation of the interface, so that the inventory interface can support lambda expressions by adding default methods.
Default method conflict resolution rules
Select a method in the parent class. If a specific implementation method is provided in a parent class, the default co-signature method in the interface will be ignored
Interface conflict. If one parent interface of a class provides a default method and another interface has a method with the same signature (whether the default method or not), the implementing class must override the method to resolve the conflict.
Thank you for reading, the above is the content of "the usage of lambda expression in Java8". After the study of this article, I believe you have a deeper understanding of the usage of lambda expression in Java8, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.