03 函数式编程接口Function

本节讲述函数式编程接口Function 的使用。

  • Function < T,R >:数据转换器,接收一个 T 类型的对象,返回一个 R类型的对象; 单参数单返回值的行为接口;提供了 apply, compose,andThen, identity 方法;
    Function的源代码:
package java.util.function;

import java.util.Objects;

@FunctionalInterface
public interface Function<T, R> {

    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);

    /**
     * Returns a function that always returns its input argument.
     *
     * @param <T> the type of the input and output objects to the function
     * @return a function that always returns its input argument
     */
    static <T> Function<T, T> identity() {
        return 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));
    }
}
  • 测试apply方法:输入一个整数n,返回一个数组
Function<Integer,Integer[]> function = new Function<Integer, Integer[]>() {
            @Override
            public Integer[] apply(Integer integer) {
                Integer[] is = new Integer[integer];
                Random random = new Random();
                for(int i=0;i<is.length;i++)
                {
                    is[i] = random.nextInt(100);
                }
                return is;
            }
        };
Integer[] is = function.apply(10);
System.out.println(Arrays.toString(is));
  • 测试执行顺序
Function<String,String> function = new Function<String, String>() {
            @Override
            public String apply(String s) {
                return s+"f1";
            }
        };

        Function<String,String> function1 = new Function<String, String>() {
            @Override
            public String apply(String s) {
                return s+"f2";
            }
        };

       String ret =  function.andThen(function1).apply("abc");//先把abc传递给function执行,再把输出传递给function1执行
        System.out.println(ret);

        String ret1 = function.compose(function1).apply("abc");//先把abc传递给function1执行,再把输出传递给function执行
        System.out.println(ret1);

        String ret3 = (String) Function.identity().apply("hello");//返回输入参数
        System.out.println(ret3);

以上就是Function的基本使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值