函数式接口

包路径:java.util.funciont

特点:

  • 具有唯一的抽象方法,有且仅有一个 (即所有的函数式接口,有且只能有一个抽象方法)
  • 加上标注 @FunctionalInterface,则会触发 JavaCompiler的检查。对于符合函数接口的接口,加不加都无关紧要,但是加上则会提供一层编译检查的保障。如果不符合,则会报错。
  • 继承后的抽象方法则不算抽象方法。例如接口实现了Object中的方法,toString()等方法。
  • 可用于lambda类型的使用方式

重点接口

  • Predicate:接收参数T对象,返回一个boolean类型对象
	/**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);
  • Consumer:接收参数T对象,没有返回对象
	/**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);
  • Function:接收参数T对象,返回R对象
	/**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);
  • Supplier:不接收任何参数,直接通过get()方法获取指定类型对象
	/**
     * Gets a result.
     *
     * @return a result
     */
    T get();
  • UnaryOperator:接收参数T对象,执行业务处理后,返回更新后的T对象

继承自:Function,通过下面的identity()方法,保证返回对象与接收对象一致

	/**
     * Returns a unary operator that always returns its input argument.
     *
     * @param <T> the type of the input and output of the operator
     * @return a unary operator that always returns its input argument
     */
    static <T> UnaryOperator<T> identity() {
        return t -> t;
    }
  • BinaryOperator:接收两个对象T和U,执行业务处理后,返回一个R对象

继承自:BiFunction,下面是继承方法

	/**
     * 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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Java中,函数式接口是指只有一个抽象方法的接口。Java 8 中引入了Lambda表达式和函数式接口,使得我们可以更方便地编写函数式代码。除了Java预定义的函数式接口外,我们还可以自定义函数式接口。 自定义函数式接口的步骤如下: 1. 创建一个接口并且使用@FunctionalInterface注解来标记它为函数式接口。 2. 在该接口中定义一个抽象方法,这个抽象方法就是我们自定义的函数式接口的唯一方法。 3. 如果需要,可以在接口中定义默认方法和静态方法。 下面是一个示例: ```java @FunctionalInterface interface MyFunctionInterface { int operation(int x, int y); default void printResult(int result) { System.out.println("Result: " + result); } } ``` 在上面的代码中,我们定义了一个自定义函数式接口 `MyFunctionInterface` ,它有一个抽象方法 `operation`,这个方法接受两个整数参数,并且返回一个整数。我们还定义了一个默认方法 `printResult`,用于打印结果。 我们可以使用Lambda表达式来创建一个实现 `MyFunctionInterface` 的对象,如下所示: ```java MyFunctionInterface sum = (x, y) -> x + y; int result = sum.operation(10, 20); sum.printResult(result); // Output: Result: 30 ``` 在上面的代码中,我们使用Lambda表达式来实现 `MyFunctionInterface` 接口,并且使用这个实现来执行加法操作。最后,我们调用 `printResult` 方法来打印结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值