Learning new features of Java 8 (1) Introduction to Lambda expressions

Lambda expressions were introduced in Java 8 and became the biggest feature of Java 8. It makes functional programming very convenient and greatly simplifies development.

Next, we will introduce Lambda expressions through example demonstrations. The content of this article is quoted from the meaning and use of Lambda expressions.

1. Grammar

A lambda expression has the following syntactic features. It consists of three parts: the first part is a formal parameter separated by commas in parentheses, and the parameter is the parameter of the method in the functional interface; the second part is an arrow symbol: ->; the third part is the method body, which can be an expression and code blocks. The syntax is as follows:

parameter -> expression body

Here are some of the most important features of Lambda expressions:

  • Optional type declaration: You don't have to declare the type of the parameter. The compiler can infer from the value of the parameter what type it is.
  • Parentheses around optional parameters: You can declare individual parameters without parentheses. But for many parameter cases, parentheses are required.
  • Optional curly braces: If there is only one statement in the expression body, then you don't have to enclose it in curly braces.
  • Optional return keyword: If the expression body has only a single expression to return the value, the compiler will do this automatically. To indicate an expression to return a value, use curly braces.

An important property of functional interfaces is that we can instantiate them using Lambdas, which allow you to treat functions as method parameters, or code as data. The introduction of lambda expressions brings many advantages to developers: before Java 8, the use of anonymous inner classes, listeners and event handlers is very verbose, and the code readability is very poor, the application of lambda expressions is Make the code more compact and readable; Lambda expressions make it easy to operate large collections in parallel, take full advantage of multi-core CPUs, and make it easier to write code for multi-core processors. Quoted from IBM - Java 8 New Features Overview .

have to be aware of is:

  • Lambda expressions are preferentially used to define the inline implementation of functional interfaces, that is, a single method has only one interface.
  • Lambda expressions eliminate the need for anonymous classes, and this Java adds concise but useful functional programming capabilities.
2. Scope

By using lambda expressions, you can refer to final variables or effectively final variables (assigned only once). If a variable is reassigned, the lambda expression will throw a compile error.

3. Method reference

A method in Java 8 is also an object that can be referenced by name. However, the only use of method references is to support shorthand for lambdas, using the method name to denote the lambda. Information such as method signatures cannot be obtained through method references. Quoted from a never-ending blog that goes up and down.

A method reference can refer to itself by its name. Method references are described by ::symbols (double colons).

It can be used to refer to the following types of methods:

  • static method
  • instance method
  • Constructor method using newoperator ( TreeSet::new)

For more introduction to method references, you can refer to this blog post - " Method References in Java 8 ".

4. Example demonstration

public class NewFeaturesTester {

    final static String salution="Hello";
    /**
     * How to operate
     * @param a first operand
     * @param b second operand
     * @param mathoperation corresponds to the specific operation
     * @return operation result
     */
    private int operate(int a,int b,MathOperation mathoperation){
        return mathoperation.operation(a,b);
    }

    /**
     * 基本语法测试
     */
    public static void test1(){
        NewFeaturesTester tester=new NewFeaturesTester();
        //带有类型声明的表达式
        MathOperation addition =(int a,int b)->a+b;
        //没有类型声明的表达式
        MathOperation subtraction=(a, b) -> a-b;
        //带有大括号,带有返回语句的表达式
        MathOperation multiplication=(int a,int b)->{return a*b;};
        //没有大括号和return语句的表达式
        MathOperation division=(int a,int b)->a/b;

        //输出结果
        System.out.println("10+5="+tester.operate(10,5,addition));
        System.out.println("10-5="+tester.operate(10,5,subtraction));
        System.out.println("10*5="+tester.operate(10,5,multiplication));
        System.out.println("10/5="+tester.operate(10,5,division));

        //没有括号的表达式
        GreetingService service1=message-> System.out.println("Hello "+message);
        //带括号的表达式
        GreetingService service2=(message)-> System.out.println("Hello "+message);

        //调用sayMessage方法输出结果
        service1.sayMessage("icarus");
        service2.sayMessage("wang");
    }

    /**
     * Lambda作用域学习
     */
    public static void test2(){
        GreetingService service=message -> {
            System.out.println(salution+message);
        };
        service.sayMessage(" lovepi");
    }

    /**
     * Lambda方法引用学习
     */
    public static void test3(){
        List names=new ArrayList();
        names.add("zhangsan");
        names.add("lisi");
        names.add("wangwu");
        names.add("zhaoliu");

        //通过System.out::println引用了输出方法
        names.forEach(System.out::println);
    }
    public static void main(String[] args){
        test3();
    }
}
Interface classes used in it
public interface MathOperation {
    int operation(int a,int b);
}
public interface GreetingService {
    void sayMessage(String message);
}
5. Summary

In this section we explained how to use lambda expressions and method references. Lambda is probably one of the most frequently involved skills in programming with the Java 8 version. It is recommended to use it instead of the previous idiom when applicable.

During the learning process, you should keep the habit of consulting official documents at any time.

Here are some links you might use:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325727831&siteId=291194637