lambda表达式

lambda表达式是java1.8的新特性,也称为函数式编程,可以简化一些操作,例如下面的例子

使用lambda之前

 new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程启动");
            }
        }).start();

 使用lambda之后

 new Thread(()->{
            System.out.println("线程启动");
        }).start();

 看起来的确简单一些,那么什么时候可以使用lambda表达式?怎样使用lambda表达式?

根据上面的例子,new Thread()里面传入一个Runnable接口的匿名类对象,看看Runnable接口如何定义的。

/* * @author  Arthur van Hoff
 * @see     java.lang.Thread
 * @see     java.util.concurrent.Callable
 * @since   JDK1.0
 */
@FunctionalInterface   //这里标注了一个函数式接口的注解,表明这里是可以使用lambda表达式
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();
}

@FunctionalInterface标准的接口就可以使用lambda表达式,默认情况下不标注也是有的,前提这里面只能有一个没有实体的方法, 怎么写?看一下run()方法,没有传入值就是写()然后->  {  }  大括号里面写逻辑 ,如果只有一行就可以省略大括号和冒号 ,如:

 new Thread(()->
            System.out.println("线程启动")
        ).start();

 方法怎么写,()里就怎么写,传几个参数,()里面就写几个参数,方法有返回值就需要有返回值。

例如下面自定义接口:定义一个有两个参数值,并返回值的方法

@FunctionalInterface
public interface Foo {

    public int add(int x,int y);

}

 测试类:

public class Lambda {

    public static void main(String[] args) {

        Foo foo = (x,y)->{
         
            return x+y;
        };
        System.out.println(foo.add(4,6));
        
    }
}

 打完收工

原文地址:https://www.cnblogs.com/tdyang/p/11869501.html