JDK8新特性之 Lambda表达式

1.为什么使用Lambda表达式

       简化匿名内部类的调用

 

2.Lambda表达式优缺点

       优点:简化代码,使代码逼格更高

       缺点:不利于debug,可读性较低

 

3.Lambda表达式规范

       ·在接口中只能有一个抽象方法

       ·@FunctionalInterface 标记该接口为函数式接口

       ·可以通过default修饰为普通方法

       ·可以定义object类中的方法 

       注意:Lambda 规定接口中只能有一个需要被实现的方法,不是规定接口中只能有一个方法

@FunctionalInterface
public interface LambdaInterface {
    
   void use();
   
   default String getStr(){
       return "str";
   }

}

       jdk 8 中有另一个新特性:default, 被 default 修饰的方法会有默认实现,不是必须被实现的方法,所以不影响 Lambda 表达式的使用。

      语法形式为 () -> {},其中 () 用来描述参数列表,{} 用来描述方法体,-> 为 lambda运算符 ,读作(goes to)。

public class Test {
    public static void main(String[] args) {
        //普通写法
        //new LambdaInterface(){
        //   @Override
        //   public void use() {
        //     System.out.println("use");
        //   }
        //}.use();
        //Lambda写法
        ((LambdaInterface) () -> System.out.println("use")).use();
    }
}

4.Lambda使用案例

      I. 调用无参函数

@FunctionalInterface
public interface LambdaInterface {
   void use();
}
public class Test {
    public static void main(String[] args) {
        ((LambdaInterface)()-> System.out.println("use")).use();
    }
}

      II.调用有参函数

@FunctionalInterface
public interface LambdaInterface {
   void add(int a , int b);
}
public class Test {
    public static void main(String[] args) {
        ((LambdaInterface)(a,b)->System.out.println(a+b)).add(1,2);
    }
}

       III.精简写法

public class Test {
    public static void main(String[] args) {
        LambdaInterface lambdaInterface = (a,b) -> {
            return a + b;
        };
        Integer add = lambdaInterface.add(1, 2);
        System.out.println(add);
    }
}
public class Test {
    public static void main(String[] args) {
        Integer add = ((LambdaInterface) (a,b) -> a + b).add(1,2);
        System.out.println(add);
    }
}

        IV.集合遍历

public class Test {
    public static void main(String[] args) {
        List<String> strList = new ArrayList<>();
        strList.add("a");
        strList.add("b");
        strList.add("c");
        strList.add("d");
        strList.forEach(t -> System.out.println(t));
    }
}

       V.集合排序

public class Test {
    public static void main(String[] args) {
       List<Integer> intList = new ArrayList<>();
       intList.add(2);
       intList.add(4);
       intList.add(6);
       intList.add(8);
       intList.sort((o1, o2) -> o1-o2);
       intList.forEach(t -> System.out.println(t));
    }
}

       VI.线程调用

public class Test {
    public static void main(String[] args) {
       new Thread(() -> System.out.println()).start();
    }
}


     

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值