Introduction to lambda expressions
A lambda expression can be understood as a concise representation of an anonymous function, which can be passed, it has no name, but it has a list of arguments, a body, a return type, or a list of exceptions that can be thrown.
- Anonymous because it does not have a definite name, unlike a method, there must be a method name.
- function Because Lambda is not a method of a particular class, but like a method, Lambda has a list of parameters, a body, a return type, and possibly thrown exceptions.
- passing A lambda expression can be passed as a parameter to a method or stored in a variable.
- Simplicity You don't have to write a lot of verbose code, it's simpler than writing anonymous inner classes.
Before using Java 8, creating a comparer would generally take the form of an inner class:
New Comparator<apple>() { publicint Compare (Apple A1, Apple A2) { return a1.getweight (). CompareTo (A2.getweight ()); };
With the code after the lambda expression, just one line of code.
Comparator<apple> byweight = (Apple A1, Apple A2), A1.getweight (). CompareTo (A2.getweight ());
The syntax structure of a lambda expression
A lambda expression consists of a parameter, an arrow, a body, and three parts.
- parameters are similar to the parameters of a method.
- The arrow points to the function body by the argument list.
- The specific operation of the principal function.
Lambda Expression Example
- (parameters), whether expression has a return value depends on the return value of the following expression.
- (parameters), {statements;} multiple statements need to be included with {}.
- (parameters), {Statements;return 23} with the statement contained in {}, if there is a return value, you need to display the return specified.
The correct expression
(string s), s.length () the expression has a String parameter S, which returns the return statement hidden by the INT,LAMBDA expression;
(Apple a), A.getweight () > 150 This expression has a parameter Apple returns a Boolean
(int x,int y), {System.out.println ("Result:"), System.out.println (x+y)} This expression has two int parameters, no return value (or void returned), A lambda expression can contain multiple statements, but must be enclosed in {} curly braces.
()--42 This expression has no arguments, but returns int
The wrong expression
(int i), return "Result:" + i; Correct notation (int i), {return "result:" + i;}
(string s), {"Zhang" + s;} correct notation (string s), {return "Zhang" + s;} or (String s), "Zhang" + s
Streamlined notation
parameter types can be omitted, such as:comparator<apple> C = (A1,A2), A1.getweight (). CompareTo (A2.getweight ());
When a lambda expression has only one argument, the parameter type can be omitted, and the parentheses can be omitted.
For example List<apple> greenapples = Filter (Inventory,a-> "green". Eqauls (A.getcolor ()));
Function-Type interface
The so-called functional interface, which is an interface, has only one abstract method. The use of a lambda expression is equivalent to the implementation of the only abstract method of the interface. The interface of a single abstract method, which is common in JDK, is commonly used:
Public Interface Comparator<t> { int compare (t o1,t O2);} Public Interface Runnable { void run ();} Public Interface EventListener { void actionperformed (ActionEvent e);}
@FunctionalInterface annotations
Java 8 is specifically for functional programming, the addition of some of the Java.util.function package interface classes, if you look at the source of these interface classes, you will notice that these functional interfaces are annotated with @functionalinterface, this annotation is used to indicate that the interface is a functional interface. If you define an interface with @functionalinterface annotations, but there are multiple abstract methods in the interface, the compiler will error when compiling.
Functional interfaces in Java 8
Java 8 has provided a large number of functional interfaces, when writing lambda expressions, often encounter, this expression to write, it is necessary to understand the corresponding function interface method parameters and return values.
predicate
@FunctionalInterface Public Interface Predicate<t> { boolean Test (T-t);}
The test method in the predicate interface, the parameter is T, returns the Boolean type, using the scene stream's filter (PREDICATE<? Super t> predicate)
Consumer
@FunctionalInterface Public Interface Consumer<t> { void accept (T-T);}
The Accept method of the Consumer interface, the parameter is T, returns void, using the scene iterable of foreach (consumer<? Super t> Action)
Function
@FunctionalInterface Public Interface Function<t, r> { R apply (T t);}
The Apply method of the Function interface, the parameter is T, the return value R, using the map in the scene stream (function<? Super T,? extends R> mapper), Flapmap (function<? Super T,? Extends R> mapper)
Method reference
In the previous lambda expression Introduction, the lambda expression is an anonymous function that can be passed as a parameter to the caller. If the parameter passed to the caller is no longer a lambda expression, but is derived from a method of a class, it is called a method reference.
For example, use lambda to represent the comparer:
Arrays.sort (list, (Apple a,apple b), A.getweight (). CompareTo (B.getweight ()));
To use method references:
Arrays.sort (list,comparator.comparing (apple::getweight))
Open comparator comparing source can see, this method has implemented the comparator's judgment rule, but this rule is based on the function (or method) of the return value, do size comparison.
Public Static extends Super U>> comparator<t> Comparing ( FunctionSuperextends u> Keyextractor) { objects.requirenonnull (keyextractor); return (Comparator<t> & Serializable) keyextractor.apply (C1). CompareTo (keyextractor.apply (C2));}
Three ways to refer to a method
The parseint method refers to a static method, for example, an integer that is written as an integer::p arseint.
A method refers to an instance method of any type, such as the length (() of a string, written as String::length.
Method refers to an instance method of an existing object, such as a local variable, obj, which has a getValue () method, written as Obj::getvalue
It is important to note that 2nd, the first parameter of lambda is the instance object of the method invocation, and the corresponding method reference, which excludes the first parameter, that is, arg0 is ignored, and only rest as the parameter.
function<string, integer> Stringtointeger = (String s), Integer.parseint (s), the corresponding method reference is Integer::p arseint
Bipredicate<list<string>, string> contains = (List, Element)-list.contains (element); In this lambda expression, Using the instance object of the first argument to invoke the Contains method, which belongs to the second way of the method reference, the corresponding method reference is list::contains. The main confusion here is that the contains () method has only one parameter, but because this method belongs to the instance method of string (not the static method of the Class), the first argument is implied.
Constructing method references
The constructor method of a class can also be referenced, using the syntax is classname::new. For example:
supplier<apple> C1 = App::new= C1.get (()
This statement refers to an argument-free construction method, or it can refer to a parameter-constructed method:
bifunction<string,integer,apple> C3 = Apple::new= c3.apply ("Gree", 110)
Here's how to construct Apple (String Color,integer weight) has two parameters.
Resources
Java 8 lambda expression