java Lamda表达式

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);
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值