1. Function interface
A functional interface is an interface with a single abstract method. The interface design is mainly to support Lambda expressions and method references, so that Java can more conveniently implement functional programming styles.
Features and uses:
- Single abstract method: Function interfaces can only have
one
Abstract method, but can haveMultiple
Default or static method. - Lambda expressions: You can use the function interface to create Lambda expressions to concisely represent anonymous functions, such as in scenarios such as collection operations and thread processing.
- Method reference: An existing method can be referenced through the type of the function interface, making the code more concise and readable.
Java 8 provides several standard function interfaces, usually located inIn the package.
Common function interfaces:
Consumer: An operation that receives an input parameter and does not return the result.
Consumer<String> printConsumer = str -> (str); ("Hello World!");
Supplier: Provided interface that does not receive parameters but returns results.
Supplier<Double> randomSupplier = () -> (); (());
Function: Receive an input parameter and return the result.
Function<Integer, String> intToString = num -> (num); ((123));
Predicate: Receives an input parameter and returns a Boolean result.
Predicate<Integer> isEven = num -> num % 2 == 0; ((5)); // false
UnaryOperator: Inherited from Function<T, T>, representing a unary operator.
UnaryOperator<Integer> square = num -> num * num; ((5)); // 25
Custom Function Interface: Just make sure there is only one abstract method in the interface.
@FunctionalInterface interface MyFunctionalInterface { void myMethod(); // Allow default methods and static methods default void anotherMethod() { ("Default method"); } } // Use custom function interfaceMyFunctionalInterface myFunc = () -> ("Hello Custom Functional Interface"); (); ();
2. Introduction to Lambda Expressions
Lambda expressions can be regarded as a way of declaring anonymous functions, allowing functions to be passed as method parameters, or used where functional interfaces are required.
Basic structure:
// parameters: parameter list, can be empty or non-empty
// ->: Arrow symbol, separating parameter list and body of Lambda expression
// expression: a single line expression as the Lambda body
(parameters) -> expression// { statements; }: The code block, as the Lambda body, can contain multiple statements and return statements
(parameters) -> { statements; }
Features of expressions:
- Simplicity and readability: Lambda expressions make the code more concise, especially when dealing with functional interfaces, eliminating redundant syntax.
- Functional programming style: Lambda expressions support functional programming, which can easily perform function transfer, method reference, streaming operations, etc.
- Closure: Lambda expressions can capture variables around them, making state management more flexible in functional programming.
Case: Through the Lambda expression asMathOperation
Interfaceoperation
The method provides four different implementations: addition, subtraction, multiplication, and division.
Interface definition:
interface MathOperation { int operation(int a, int b); }
Use Lambda expressions to implement this interface to pass different mathematical logic:
public class LambdaDemo { public static void main(String[] args) { // Lambda expressions implement addition MathOperation addition = (int a, int b) -> a + b; ("10 + 5 = " + operate(10, 5, addition)); // Lambda expressions implement subtraction MathOperation subtraction = (a, b) -> a - b; ("10 - 5 = " + operate(10, 5, subtraction)); // Lambda expression implements multiplication MathOperation multiplication = (int a, int b) -> { return a * b; }; ("10 * 5 = " + operate(10, 5, multiplication)); // Lambda expression implements division MathOperation division = (a, b) -> a / b; ("10 / 5 = " + operate(10, 5, division)); } private static int operate(int a, int b, MathOperation mathOperation) { return (a, b); } }
3. External parameters of Lambda expression
Lambda expressions have their own specific scope rules, which can capture and access the variables around them. They can refer to external variables at will, but if the external variable is declared in the current scope, a second assignment cannot be performed, even after the lambda statement.
Local variables: Lambda expressions can access local variables of the method they are in, but these variables must be implicitly final or in fact final (final
). This means that the variable will not change once assigned. The values of these local variables are not allowed to be modified internally by Lambda expressions, otherwise the compiler will report an error.
public class LambdaScopeDemo { public static void main(String[] args) { int num = 10; // Local variables MathOperation addition = (int a, int b) -> { // num = 5; // Error! Lambda expressions cannot modify the value of local variables // The local variable num is accessed here return a + b + num; }; ((5, 3)); } }
Field: A Lambda expression can access fields (member variables) of an external class, including instance fields and static fields.
public class LambdaScopeDemo { private static int staticNum; // Static fields private int instanceNum; // Instance field public void testLambdaScope() { MathOperation addition = (int a, int b) -> { // Access instance fields and static fields int result = a + b + instanceNum + staticNum; return result; }; ((5, 3)); } }
Default method of an interface: A Lambda expression can access the default method defined in the interface, but cannot access the instance fields defined in the interface.
IV. Lambda Example
Common scenarios when using Lambda expressions include traversal, sorting, filtering, and combining them with functional interfaces.
Common Java 8 Lambda expression examples:
Traversal collection
public static void main(String[] args) { List<String> names = new ArrayList<>(); ("Alice"); ("Bob"); ("Charlie"); // Use Lambda expressions to traverse the collection (name -> (name)); }
Use functional interface for calculation
Reference: 2. Introduction to Lambda Expressions
Conditional filtering using functional interface
public static void main(String[] args) { List<Integer> numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // Use Lambda expression to filter even numbers ("even:"); filter(numbers, n -> n % 2 == 0); // Use Lambda expression to filter numbers greater than 5 ("Numbers greater than 5:"); filter(numbers, n -> n > 5); } private static void filter(List<Integer> numbers, Predicate<Integer> condition) { for (Integer number : numbers) { if ((number)) { (number + " "); } } (); }
Use Comparator for collection sorting
public static void main(String[] args) { List<String> names = new ArrayList<>(); ("Alice"); ("Bob"); ("Charlie"); // Sort using Lambda expressions (based on string length) ((s1, s2) -> () - ()); // Output the sorted result (name -> (name)); }
Execute code blocks using Runnable
Reference: 5. Runnable Lambda Expressions
5. Runnable Lambda expression
Use Lambda expressions to implement conciselyRunnable
Instantiation of the interface.Runnable
An interface is a function interface that contains only one abstract methodvoid run()
, used to define a task that can be executed by a thread.
Anonymous inner class (Java 7 and before):
Runnable runnable = new Runnable() { @Override public void run() { ("Running in a separate thread"); } }; Thread thread = new Thread(runnable); ();
Lambda expressions (Java 8+):
Runnable runnable = () -> { ("Running in a separate thread"); }; Thread thread = new Thread(runnable); ();
A simpler way: the task is very simple and can be further simplified, and pass the Lambda expression as a parameter to theThread
Constructor:
Thread thread = new Thread(() -> { ("Running in a separate thread"); }); ();
This way avoids explicit declarationRunnable
Variables to make the code more compact and readable.
Case:
public static void main(String[] args) { // Create a new thread using Lambda expression Thread thread = new Thread(() -> { for (int i = 0; i < 5; i++) { ("Thread execution:" + i); try { (1000); } catch (InterruptedException e) { (); } } }); // Start the thread (); }
The above is the detailed content of in-depth analysis of Java function interfaces and Lambda expressions. For more information about Java function interfaces, please pay attention to my other related articles!