JDK8特性:lambda表达式简单使用介绍

新公司的代码中很多使用的 -> 这样的写法,看得我一脸懵逼,查了一下才知道这事JDK8提供的新特性,lambda表达式,在一定程度上可以简化某些代码的写法,下面我们就来一起看一下。



1.对匿名内部实现的支持:

        在java中使用多线程,一般会添加一个java类实现Runable接口或者继承Thread类。也还有一种比较粗暴的方式就是创建匿名内部类,如:

//标准写法
        Runnable old = new Runnable() {
            @Override
            public void run() {
                System.out.println("this is easy to read");
            }
        };
        Thread thread1 = new Thread(old);
        thread1.start();

        lambda提供了对内部类的支持,在JDK8下,下面的写法得到了和上面一样的效果:

        //lambda写法
        //->的写法指向的大括号中就是run方法的实现
        Thread thread2 = new Thread(() -> {
            System.out.println("how this could be");
        });
        thread2.start();

        当需要实现的对象有且仅有一个抽象方法时,我们可以使用lambda表达式, ->  指向一个{},在{}中进行具体实现。

    怎么样判断对象有且仅有一个抽象方法比较麻烦,JDK8还引入了另外一条新特性,函数式接口注解:@FunctionalInterface

       JDK8的Runable类源码也变成了:

@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();
}

        简单的就是说,Funcationallnterface注解可以添加在仅包含一个抽象方法的接口上。

        JDK8的API文档中对Funcationallnterface也做了关于lambda表达式的解释:

             Note that instances of functional interfaces can be created with lambda expressions, method references, or constructor references.

        简单翻译就是有Funcationallnterface的类,支持lambda表达式进行使用。这里的Funcationallnterface更像是一个标识性注解而非功能性注解。


2.对迭代循环的支持:

          现在的循环写法一般是这样的:

        //通常写法
        List<String> arrList = Arrays.asList("1", "2", "3", "4");
        for (String str: arrList ) {
            System.out.println(str);
        }

            引入lambda表达式后,可以写成这样:

        //lambda写法
        arrList.forEach(str -> {
            System.out.println(str);
        });
            这里ArryList的forEach方法也是在JDK8的版本中新增的。



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值