A journey to Java Lambda expressions

Source: Internet
Author: User

A journey to Java Lambda expressions

JDK 8's support for Lambda function programming is nothing more than introducing some new syntax structures. It is an innovative way of coding after the Generics introduced by JDK 5, if you don't keep up, I'm afraid you will think that Java code has become a Martian language in a short time. Java supports parallel processing in a multi-core CPU environment at the language level. This is evident in Stream API. Many mainstream languages have been available before Java, like C # And C ++, it supports Lambda function programming. The introduction of Lambda support in Java is not difficult to understand.

There are two things to understand to write Lambda code in Java. One is a Lambda expression. The other is the function interface. This article focuses on these two points.

Lambda expressions-Lambda expressions are actually an anonymous method. This method cannot be executed by itself. It can only be used to implement methods defined in function interfaces. When Lambda expressions implement a function interface, an anonymous class is generated. Function interfaces-function interfaces are interfaces that contain only one abstract method. methods defined in interfaces before JDK 8 are abstract methods. After JDK 8, the method defined in the interface can use the default keyword to define the default implementation for the interface method. Once the default implementation is defined, it cannot be called an abstract method. The Runnable and Comparable interfaces previously defined in Java can all be called function interfaces. Lambda expressions are separated from function interfaces in Java, so they can only be considered an unexecutable expression. It is not until Lambda expressions are used to implement a function interface that can be run in the Java World.

Let's use the function interface to analyze the Lambda expression.


Lambda expressions can be expressed as (p1, p2 ,....) -> Simple expression | code block

Where-> is the Lambda operator, and the left side is the list of parameters required by the expression, separated by commas. If there is no parameter, it is an empty parentheses (). The right side is the specific content of the expression, which can be divided into simple expressions and code blocks containing complex logic. A simple expression can only contain a single expression, but a code block is an anonymous code block that can contain more complex logic.


Let's look at two examples of simple expressions.

()-> “Hello, Lambda”

This simple example does not accept any parameters, so there is only one bracket on the left. The right side is an expression that returns a simple string. Similar to the following Java code

String sayHello(){  Return “Hello, Lambda”;}

The first function interface can be run in combination with a Lambda expression.

interface Hello4Lambda {    public String sayHello();}public class HelloLambda {    public static void main(String[] args){        Hello4Lambda hl  = () ->  "Hello,Lambda.";        System.out.println(hl.sayHello());    }}

Let's look at another example with parameters.

(name) -> “Hello, ” + name


This Lambda expression is equivalent to the following Java code

String sayHello(String name){  Return “Hello, ” + name;}

The executable code is as follows:

interface Hello4Anyone {    public String sayHello(String name);}public class HelloAnyone {    public static void main(String[] args){        Hello4Anyone hw  = (name) ->  "Hello," + name;        System.out.println(hw.sayHello("Matt"));    }}

You may find that the parameters in Lambda expressions do not specify the parameter type. Java automatically pushes the parameter type based on the function interface implemented by the Lambda expression. For simple expressions, the calculation results must be returned by default. This means that the implemented function interface must have a return value instead of void. The following code reports a compilation error because the interface defines an interface method that does not return a value.

interface Hello4Anyone {    public void sayHello(String name);}public class HelloAnyone {    public static void main(String[] args){        Hello4Anyone hw  = (name) ->  "Hello," + name;        System.out.println(hw.sayHello("Matt"));    }}

Let's take a look at the example with default implementation. This example will cause a compilation error because the interface we define is not a function interface and there is no abstract method.

Interface Hello4Anyone {public default String sayHello (String name) {// return "Hello," + name ;};} by default ;};} public class HelloAnyone {public static void main (String [] args) {Hello4Anyone hw = (name)-> "Hello," + name; // a compilation error occurs in System. out. println (hw. sayHello ("Matt "));}}

Complex code blocks in Lambda expressions allow us to perform more complex operations than simple expressions. We only need to place the code in, add the return keyword at the end of the Code to return the computation result. Of course, you really need to return the result. If the function interface you are trying to implement does not need to return any returned values, you do not need to return any results in your Lambda code block.

Interface DoubleCalculate {double Sum (double [] arr);} public class DoubleCalculator {public static void main (String [] args) {double [] a = new double [10]; for (int I = 0; I <. length; I ++) a [I] = Math. random () * 100; DoubleCalculate dc = (arr)-> {double sum = 0; for (int j = 0; j

In this example, the elements in a double array are summed. We use the Lambda expression code block to implement this logic. However, if we try to sum the int array, the interface DoubleCalculate cannot receive the int type array. For this reason, we may need to define another interface function specifically for int-type arrays.


Interface IntCalculate {int Sum (int [] arr);} public class IntCalculator {public static void main (String [] args) {int [] a = new int [10]; for (int I = 0; I <. length; I ++) a [I] = (int) (Math. random () * 100); IntCalculate dc = (arr)-> {int sum = 0; for (int j = 0; j

In this way, the code will appear redundant. Can we use the paradigm to normalize the parameters of abstract methods in function interfaces? The answer is yes. Support for JDK 5 can also be applied to function interfaces.


Interface Calculate
   
    
{T Sum (T [] arr);} public class GenericCalculator {public static void main (String [] args) {// For double array. double [] a = new Double [10]; for (int I = 0; I <. length; I ++) a [I] = Math. random () * 100; Calculate
    
     
Dc = (arr)-> {double sum = 0; for (int j = 0; j ic = (arr)-> {int sum = 0; for (int j = 0; j
     

However, Lambda expressions cannot support the normal type. We can see that the code blocks of two different Lambda expressions are for Double and Integer respectively.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.