@FunctionalInterface使用和自定义
@FunctionalInterface使用和自定义
这个是java1.8加入的新特性,这个有时候有时候业务重复单对象不重复是,这时函数是编程就能解决这个问题,相当于回调函数,可以让参数方法里外传来去。
例子
使用已有的函数对象
@FunctionalInterface
public interface BiFunction<T, U, R> {
/**
* Applies this function to the given arguments.
*
* @param t the first function argument
* @param u the second function argument
* @return the function result
*/
R apply(T t, U u);
/**
* Returns a composed function that first applies this function to
* its input, and then applies the {@code after} function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <V> the type of output of the {@code after} function, and of the
* composed function
* @param after the function to apply after this function is applied
* @return a composed function that first applies this function and then
* applies the {@code after} function
* @throws NullPointerException if after is null
*/
default <V> BiFunction<T, U, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t, U u) -> after.apply(apply(t, u));
}
}
使用方式
public static void main(String[] args) {
BiFunction<Integer, Long, String> a = (t, u) -> String.valueOf(t+u);
System.out.println(a.apply(1,2L));
}
这是java1.8提供的所有函数,可以自行研究,如果不够我们还可以自定义
自定义函数
定义函数
@FunctionalInterface
public interface ZkqFunction<Z,K,Q> {
/**
* Applies this function to the given arguments.
* @param z 第一个参数
* @param k 第二个参数
* @return Q 返回值
*/
Q zkq(Z z,K k);
}
使用函数
public static void main(String[] args) {
ZkqFunction<String,String,String> zk = (z,k) -> z+k+"q";
System.out.println(zk.zkq("z","k"));
}
输出
zkq
var code = “e05eb0e0-9237-4c84-8aef-0609e1b413e3”
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器