Function函数式接口

本文介绍Java中的高阶函数概念及Function、BiFunction函数式接口的应用。通过实例展示了如何利用这些接口进行灵活的编程操作,包括apply、compose和andThen等方法的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

高阶函数:如果一个函数接收一个函数作为参数,或者返回一个函数作为返回值,那么该函数就叫做高阶函数。

Function函数式接口:传入一个参数,根据参数可以做一些操作,然后返回一个值(参数和返回值得类型是泛型)

@FunctionalInterface
public interface Function<T, R> {
    R apply(T t);
    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }
    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }
    static <T> Function<T, T> identity() {
        return t -> t;
    }
}

使用Function函数式接口,里面抽象方法是apply,接收一个参数,同时会返回一个参数:

public class MyTest4 {
    public static void main(String[] args) {
        MyTest4 test4 = new MyTest4();
        //下面几种调用operate的形式使用Function函数式接口实现,传递的是行为,如果采用传统的方式,则下面几种不同的操作必须定义不同的方法才能够实现
        //减少方法的定义,重用性更好
     test4.operate(1,value -> {return value + 1;});
        test4.operate(2,value -> value * value);
        test4.operate(3,value -> value - 1);
    }
    public int operate(int a, Function<Integer,Integer> function){
        return function.apply(a);
    }
}

compose和andThen函数的应用:

public class MyTest5 {
    public static void main(String[] args) {
        MyTest5 test5 = new MyTest5();
        //输出12,compose函数是先将输入参数传递func2中的apply方法,返回值作为func1的参数,然后执行func1的apply方法
        System.out.println(test5.oper1(2,value -> value * 3,value -> value * value));
        //输出36,andThen方法是将输入参数传递给当前调用Function,当前调用的Function是func1,执行完后将返回值作为func2的参数传入,并执行func2的apply方法
        System.out.println(test5.oper2(2,value -> value * 3,value -> value * value));
    }

    public int oper1(int a, Function<Integer,Integer> func1,Function<Integer,Integer> func2){
        return func1.compose(func2).apply(a);
    }

    public int oper2(int a, Function<Integer,Integer> func1,Function<Integer,Integer> func2){
        return func1.andThen(func2).apply(a);
    }
}

BiFunction函数式接口,是Function函数式接口的一种变体,接收两个参数,返回一个值;可以看到BIFunction中只有andThen方法,而没有compose方法,如果提供compose方法,则compose方法中的参数一定是BIFunction类型,因为传入的是两个参数,但是BIFunction执行apply方法之后只返回一个参数,那么compose方法中执行完before中的apply之后,无法再执行调用的BiFunction中的apply方法,因为此时参数只有一个了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值