java中lambda表达式的应用

lambda表达式

Lambda 允许把函数作为一个方法的参数(函数作为参数传递进方法)

使用 Lambda 表达式可以使代码变的更加简洁紧凑。

语法格式:
(parameters) -> expression

(parameters) ->{ statements; }

常见应用:四大核心函数接口
有参无返回值 Consumer
无参有返回值 Supplier
有参有返回值 Function
断言式接口 Predicate

实例有两种形式:

形式一:

 public static void test1(){  //断言型
        Predicate<Integer> p = (num) -> num<10;
        System.out.println(p.test(100));

    }
    public static void test2(){ //消费型
        Consumer<String> c = x -> System.out.println(x+"吃");
        c.accept("小鸡");

    }

    public static void test3(){ //供给型
        Supplier<Integer> w = () -> (int)(Math.random()*900);
        System.out.println(w.get());

    }

    public static void test4(){ //函数型
        Function<String,Integer> f = (x) -> (int)(Math.random()*900);
        System.out.println(f.apply("444"));
    }

形式二:

 public static String upper( Function<String,String> f,String str){
        return f.apply(str);
    }

    public static void test4_1(){   //第二种形式
        upper(x->x.toUpperCase(),"hello");



 public static Integer random( Supplier<Integer> w){
        return w.get();
    }

    public static void test3_1(){
        int i = random(()->(int)(Math.random()*900));
        System.out.println(i);
    }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值