java Lamda表达式

2022-07-29 12:46:25

java8新特性,Lamda是一个匿名函数,类似Python中的Lamda表达式、js中的箭头函数,目的简化操作。

为什么要使用Lamda?
可以对一个接口进行非常简洁的实现。

Lamda对接口的要求?
接口中定义的抽象方法有且只有一个才可以。

传统实现一个接口需要这样做:
方法一:

// 实现接口,同时必须重写接口中抽象方法
class Test implements IntrfacefN {
    @Override
    public void getUser(int a, int b) {
    }
}
// @FunctionalInterface 注解意思:函数式接口,用来做规范,有这个注解,说明此接口有且只有一个抽象方法!!! 
@FunctionalInterface
interface IntrfacefN{
    public void getUser(int a, int b);
}

方法二:
匿名表达式

public class Lamda {
    public static void main(String[] args) {
        // 匿名表达式实现接口
        IntrfacefN intrfacefN1 = new IntrfacefN(){
            @Override
            public void getUser(int a, int b) {
                
            }
        };
    }
}


使用Lamda -> 只关注参数和方法体(返回值类型不需要写、类型不需要写)

public class Lamda {
    public static void main(String[] args) {
        // 实现接口,后边匿名函数就是重写的方法!
        IntrfacefN intrfacefN = (int a, int b) -> System.out.println(a-b);
        intrfacefN.getUser(1, 2);
    }
}

不定参

@FunctionalInterface
interface IntrfacefN{
    public void getUser(int... a);
}
public class Lamda {
    public static void main(String[] args) {
        IntrfacefN intrfacefN = (int ...a) -> {
            for (int i = 0; i < a.length; i ++) {
                System.out.println(a[i]);
            }
        };
        intrfacefN.getUser(1, 2);
    }
}

可省略的部分

参数类型

IntrfacefN intrfacefN = (a, b) -> System.out.println(a-b);

小括号
前提只有一个参数情况

IntrfacefN intrfacefN = a -> System.out.println(a);

方法大括号
方法体只有一句代码

IntrfacefN intrfacefN = (a, b) -> System.out.println(a-b);

返回return

如果大括号中只有一条返回语句,则return 也可以省略

IntrfacefN intrfacefN = (a, b) -> {
    return a-b
};
// 省略之后写法:
IntrfacefN intrfacefN = (a, b) -> a-b;

高级部分

方法的引用

将一个Lamda表达式的实现指向一个已实现的方法,这样做相当于公共逻辑部分的抽离,实现复用。

public class Lamda {
    public static void main(String[] args) {
        IntrfacefN intrfacefN = (a, b) -> add(a, b);
        intrfacefN.getUser(1, 2);
    }
    public static void add(int a, int b) {
        System.out.println(a+b);
    }
}

@FunctionalInterface
interface IntrfacefN{
    public void getUser(int a, int b);
}

还有更简洁的实现:
方法隶属者:语法 - 方法隶属者::方法名
补充下:这个方法隶属者,主要看方法是类方法还是对象方法,如果是类 -方法类::方法名 ,如果是对象方法 -new 方法类::方法名

public class Lamda {
    public static void main(String[] args) {
        IntrfacefN intrfacefN = Lamda::add;
        intrfacefN.getUser(1, 2);
    }
    public static void add(int a, int b) {
        System.out.println(a+b);
    }
}

@FunctionalInterface
interface IntrfacefN{
    public void getUser(int a, int b);
}


  • 作者:@红@旗下的小兵
  • 原文链接:https://blog.csdn.net/qq_42778001/article/details/118354490
    更新时间:2022-07-29 12:46:25