Java中lambda表达式

Java8引入了很多新特性,其中就包括了Lambda 表达式以及stream,今天就通过简单几句话说说lambda到底是个什么东西。

首先lambda作用是什么?

         Lambda 表达式可以使代码变的更加简洁,换句话说就是让你可以写出优雅的代码

public static void main(String[] args) {
        final int num=10;
        //1.7
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(num);
            }
        });
        //1.8
        Thread thread1=new Thread(()-> System.out.println(num));

        thread.start();
        thread1.start();
    }

     上面我们使用lambda表达式替换掉了匿名内部类使得代码变得更加简洁了

lambda表达式是什么

那么lambda表达式是什么呢?

        java8允许将一个函数写成lambda表达式的形式作为参数传入方法中

那么这是一个怎么样的函数呢?

        他其实就是接口中方法的实现,这个函数在一个接口中被定义,并且这个接口只能定义它一个函数这种接口叫做“函数式接口”

也就是说lambda其实是接口中方法的实现,所以lambda表达式的参数及返回类型需要和接口中方法一致

 

我们来对上边的例子来进行修改便于更容易理解:

首先新建MyThread类继承runnable接口

public class MyThread implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i <10 ; i++) {
            System.out.println("1.7 print :" +i);
        }
    }
}

然后去创建线程

public static void main(String[] args) {
        final int num=10;
        //1.7
        Runnable runnable1=new MyThread();
        Thread thread1=new Thread(runnable1);

        //1.8
        Runnable runnable2=()-> {
            for (int i = 0; i <num ; i++) {
                out.println("1.8 print :"+i);
            }};
        Thread thread2=new Thread(runnable2);

        thread1.start();
        thread2.start();

    }

       从上面代码中可可以看出,不使用lambda需要新建类去继承runnable接口。而使用lambda可以很方便的实现方法并作为参数传入方法中。

再来看看runnable接口,他的确只定义了一个方法,并且通过@FunctionalInterface注解标注防止定义其他方法使它变成“非函数式接口”

@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

最后在来看看其他几种lambda表达式的形式

 * () -> 5  无参返回 5
 * x -> 2 * x  参数为x 返回2x
 * (x, y) -> x – y  两个参数,返回x-y
 * (int x, int y) -> x + y  两个int型参数
 * (String s) -> System.out.print(s)  无返回值或者说返回void

 

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值