函数式接口

函数式接口,Functional Interface 是一个有且仅有一个的抽象方法,可以有多个非抽象方法的接口

函数式接口可以被隐式的转换为lambda表达式

1.定义

@FunctionalInterface
interface GreetingService {
	void sayMessage(String message);
}

可以用lambda表达式,表示这个GreetingService接口的实现

GreetingService greetService = message -> System.out.println("hello" + message)

2. java8已有的函数式接口

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

Callable接口

@FunctionalInterface
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

等等

3.函数式接口示例

Predicate接口是一个函数式接口,接受参数T,返回一个布尔值结果
包含多种默认方法,将Predicate组合成其他复杂逻辑

// 定义一个返回Predicate接口的函数,jdk8以前用的是匿名内部类方式,函数里用的是lambda表达式
public Predicate<NotificationContext> isRdsResourcePredicate(){
        return c -> delta.api.enums.ResourceType.RDS.getInnerResTypeSet().contains(c.resourceType.getSourceName());
    }
	
	// 定义方法判断是否是rds资源
    public boolean isRdsResource(NotificationContext context) {
        return isRdsResourcePredicate().test(context);
    }	
posted @   SpecialSpeculator  阅读(33)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示