Java8 特性(二)—— Lambda表达式

本文深入解析Java8中的Lambda表达式,介绍其基本语法、如何使用以及各种应用场景,包括无参数、有参数、无返回值和有返回值的情况,帮助读者掌握这一重要特性。

 

Java8 特性(二)—— Lambda表达式

一、Lambda表达式

  Lambda是Java8的一个语法糖,它其实是匿名函数,通过约定好怎么传入参数,怎么返回参数,由编译器负责参数类型的猜测并执行结果。

二、Lambda表达式的基本语法

   /**
     * Lambda表达式的基本语法
     */
    public void example(){
        //语法格式
        //(parameters) -> expression
        //(parameters) -> { statements; }
        //即"->"操作符将Lambda表达式分为两个部分:左侧为参数列表,右侧为Lambda体。
        //每一个Lambda表达的返回值都是一个函数式编程的接口
    }

三、Lambda表达式的简单使用示例

   /**
     * 无参数,无返回
     */
    @Test
    public void example2(){
        Runnable hello_lambda1 = () -> System.out.println("Hello Lambda");
        hello_lambda1.run();
        //或
        Runnable hello_lambda2 = () -> {
            System.out.println("Hello Lambda");
        };
        hello_lambda2.run();
    }
 
    /**
     * 无参数,有返回
     */
    @Test
    public void example3(){
        Supplier<Integer> supplier1 = () -> 10;
        System.out.println(supplier1.get());
        //或
        Supplier supplier2 = () -> {
            return 10;
        };
        System.out.println(supplier2.get());
    }
 
    /**
     * 有一个参数,无返回
     */
    @Test
    public void example4(){
        Consumer<String> consumer1 = x -> System.out.println(x);
        consumer1.accept("Hello Lambda");
        //或
        Consumer<String> consumer2 = (x) -> System.out.println(x);
        consumer2.accept("Hello Lambda");
        //或
        Consumer<String> consumer3 = x -> {
            System.out.println(x);
        };
        consumer3.accept("Hello Lambda");
    }
 
    /**
     * 有一个参数,有返回值
     */
    @Test
    public void example5(){
        IntFunction<Integer> intFunction1 = x -> x + 10;
        System.out.println(intFunction1.apply(10));
        //或
        IntFunction<Integer> intFunction2 = (x) -> {
            return x + 10;
        };
        System.out.println(intFunction2.apply(10));
    }
 
    /**
     * 有多个参数,无返回值
     */
    @Test
    public void example7(){
        ObjIntConsumer<Integer> objIntConsumer = (x,y) -> {
            System.out.println(x + y);
        };
        objIntConsumer.accept(10,20);
        //或
        BiConsumer<Integer,Integer> biConsumer = (Integer x, Integer y) -> {
            System.out.println(x + y);
        };
        biConsumer.accept(10,20);
    }
 
    /**
     * 有多个参数,有返回值
     */
    @Test
    public void example6(){
        IntBinaryOperator intBinaryOperator = (x,y) -> {
          return x > y ? x : y;
        };
        System.out.println(intBinaryOperator.applyAsInt(10,20));
        //或
        BinaryOperator<Integer> binaryOperator = (Integer x, Integer y) -> {
            return x > y ? x : y;
        };
        System.out.println(binaryOperator.apply(10,20));
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值