java lambda 自定义

1.概念

lambda表达式是JAVA8中提供的一种新的特性,它支持Java也能进行简单的“函数式编程”。 
它是一个匿名函数,Lambda表达式基于数学中的λ演算得名,直接对应于其中的lambda抽象(lambda abstraction),是一个匿名函数,即没有函数名的函数。

2.使用

   2.1首先新建函数式接口,eg Runnable。这里需要注意:函数式接口智能有一个方法

   Runnable接口

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

     2.2  在使用方法是,就可以把接口作为参数传进去

public Thread(Runnable target) {
    init(null, target, "Thread-" + nextThreadNum(), 0);
}

 

     2.3 这样新建的线程的时候可以讲函数时接口作为参数

new Thread(()->{System.out.println("hello World");})

3.::  操作符使用

class Zoo {
    private List animalList;
    public Zoo(List animalList) {
        this.animalList = animalList;
        System.out.println("Zoo created.");
    }
}

interface ZooFactory {
    Zoo getZoo(List animals);
}

 class ConstructorReferenceExample {

    public static void main(String[] args) {
        //following commented line is lambda expression equivalent
        //ZooFactory zooFactory = (List animalList)-> {return new Zoo(animalList);};
        ZooFactory zooFactory = Zoo::new;
        System.out.println("Ok");
        Zoo zoo = zooFactory.getZoo(new ArrayList());
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值