Detailed explanation of Lambda expression of Java 8
This article introduces the relevant knowledge of "detailed interpretation of Lambda expressions in Java 8". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Functional interface
An interface that contains only one method is called a functional interface, and Lambda expressions are used where any functional interface applies.
Java.awt.event.ActionListener is a functional interface because it has only one method: void actionPerformed (ActionEvent). In Java 7, we will write the following code:
Button.addActionListener (new ActionListener () {public void actionPerformed (ActionEvent e) {ui.dazzle (e.getModifiers ());}})
In Java 8, it can be simplified to:
Button.addActionListener (e-> {ui.dazzle (e.getModifiers ());})
The compiler knows that Lambda expressions must conform to the definition of the void actionPerformed (ActionEvent) method. It looks like the Lambda entity returns void, but in fact it can infer that the type of parameter e is java.awt.event.ActionEvent.
Function set
The class library of Java 8 contains a new package, java.util.functions, with many new functional interfaces that can be used with the collection API.
Java.util.functions.Predicate
Use predicates (Predicate) to filter the collection:
List names = Arrays.asList ("Alice", "Bob", "Charlie", "Dave"); List filteredNames = names .filter (e-> e.length () > = 4) .into (new ArrayList ()); for (String name: filteredNames) {System.out.println (name);}
Here are two new ways:
Iterable filter (Predicate