• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
职业熬夜选手
博客园    首页    新随笔    联系   管理    订阅  订阅

@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”

posted @ 2023-03-19 22:29  职业熬夜选手  阅读(66)  评论(0)    收藏  举报  来源
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3