一文看懂Lambda表达式简化匿名函数式接口

匿名函数式接口用法

  1. 只要是函数式接口就可以用Lambda表达式简化。
  2. 接口中有且只有一个未实现的方法就叫函数式接口。
  3. 可以在接口上添加检查注解@FunctionalInterface 查看是否符合函数式接口规范。
  4. Lambda表达式是在程序运行的时候动态生成class。

完整写法

参数列表(参数类型 参数名) + 箭头 -> + 方法体 {代码块}

public class Test {

    @FunctionalInterface
    interface LambdaInterface{
        int way(int i,int j);
    }

    public static void main(String[] args) {

        LambdaInterface lambdaInterface = (int i,int j) -> {
            return i+j;
        };

        int sum = lambdaInterface.way(2, 2);

        LambdaInterface lambdaInterface1 = (int i,int j) -> {
            return i-j;
        };

        int sub = lambdaInterface1.way(2, 1);

        System.out.println("两数相加值为:" + sum);
        System.out.println("两数相减值为:" + sub);
    }

}

简化写法

  1. 参数类型可以不写,只写参数名。参数列表最少只有一个()或者只有一个参数名。
  2. 方法体只有一句话的情况下,{}可以省略
public class Test {

    @FunctionalInterface
    interface LambdaInterface{
        int way(int i);
    }

    public static void main(String[] args) {

        LambdaInterface lambdaInterface = i -> i+1;

        int way = lambdaInterface.way(2);

        System.out.println("当前值默认加一:" + way);

    }

}

Function函数式接口

java.util.function包下的所有function定义

Supplier

提供型接口: 没有参数,只有返回值
调用的函数方法:get

public class Test {

    public static void main(String[] args) {

        Supplier<String> supplier = () -> "岳阳楼下喝可乐";
        
        System.out.println("输入值为:" + supplier.get());

    }

}

Predicate

断言型接口:有一个输入参数,返回值只能是布尔值
调用的函数方法:test

public class Test {

    public static void main(String[] args) {

        Predicate<String> isNull = str -> str.isBlank() ;
        
        System.out.println("输入是否为空" + isNull.test(""));

    }

}

Function

函数型接口, 有一个输入参数 T ,有一个输出 R
调用的函数方法:apply

public class Test {

    public static void main(String[] args) {

        Function<String,Integer> function = Integer::parseInt;

        System.out.println("字符串类型转数值类型:" + function.apply("123"));

    }

}

Consumer

消费型接口: 只有输入,没有返回值
调用的函数方法:accept

public class Test {

    public static void main(String[] args) {

        Consumer<Integer> consumer = num ->{
            if (num % 2 == 0){
                System.out.println("当前值"+num+"为偶数");
            }else {
                System.out.println("当前值"+num+"为奇数");
            }
        };

        consumer.accept(13);

    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值