淘先锋技术网

首页 1 2 3 4 5 6 7

本节讲述函数式编程接口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的基本使用。