Java learning summary: 24

Lambda expression

Lambda expression refers to a simplified definition form applied in the context of a single abstract method (SAM) interface, which can be used to solve the complex problem of anonymous inner class definition.
Lambda expression syntax:

(参数)->方法体

Method body equivalent to subclass overriding abstract method

Example: Getting started with Lambda expressions

package Project.Study.Lambda_test;

interface IMessage{
    public void print();
}
public class Test1 {
    public static void main(String [] args){
    	//此处为Lambda表达式,没有任何输入参数,只是进行输出操作
        fun(()->System.out.println("Hello World"));
    }
    public static void fun(IMessage msg){
        msg.print();
    }
}
//结果:
//Hello World

Example: Using anonymous inner classes for the above operations

package Project.Study.Lambda_test;

interface IMessage{
    public void print();
}
public class Test1 {
    public static void main(String [] args){
        fun(new IMessage() {	//等价于Lambda表达式定义
            @Override
            public void print() {
                System.out.println("Hello World");
            }
        });
    }
    public static void fun(IMessage msg){
        msg.print();
    }
}
//结果:
//Hello World

In order to distinguish the interface used by the Lambda expression, you can use the "@FunctionalInterface" annotation on the interface to declare that this is a functional interface. Only one abstract method is allowed to be defined.
Example: Functional interface

@FunctionalInterface
interface IMessage{
    public void print();
}

Example: Define a method with parameters and return values

package Project.Study.Lambda_test;

interface IMessage{
    public int add(int x,int y);
}
public class Test1 {
    public static void main(String [] args){
        fun((s1,s2)->{
            return s1-s2;
        });
    }
    public static void fun(IMessage msg){
        System.out.println(msg.add(10,20));
    }
}
//结果:
//-10

Example: Passing variable parameters

package Project.Study.Lambda_test;
@FunctionalInterface
interface IMessage2{
    public int add(int...args);
    static int sum(int...args){	//此方法可以由接口名称直接调用
        int sum=0;
        for(int temp:args){
            sum+=temp;
        }
        return sum;
    }
}
public class Test2 {
    public static void main(String [] args){
    //在Lambda表达式中则直接调用接口里定义的静态方法
        fun2((int...param)->IMessage2.sum(param));
    }
    public static void fun2(IMessage2 msg){
        System.out.println(msg.add(10,20,30));	//传递可变参数
    }
}

49 original articles published · Liked25 · Visits1524

Guess you like

Origin blog.csdn.net/weixin_45784666/article/details/104911275