函数式接口
函数式接口,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
包含多种默认方法,将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);
}
原创:做时间的朋友
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示