预定义的函数式接口 Function


函数接口: Function<T, R> 

方法定义: R apply(T t);

说明: 函数转换,输入类型T,输出类型R

 

接口源码

 @FunctionalInterface
    public interface Function<T, R> {
        
        /**
         * 抽象方法: 根据一个数据类型T加工得到一个数据类型R
         */
        R apply(T t);

        /**
         * 组合函数,调用当前function之前调用
         */
        default <V> java.util.function.Function<V, R> compose(java.util.function.Function<? super V, ? extends T> before) {
            Objects.requireNonNull(before);
            return (V v) -> apply(before.apply(v));
        }

        /**
         * 组合函数,调用当前function之后调用
         */
        default <V> java.util.function.Function<T, V> andThen(java.util.function.Function<? super R, ? extends V> after) {
            Objects.requireNonNull(after);
            return (T t) -> after.apply(apply(t));
        }

        /**
         *  静态方法,返回与原函数参数一致的结果。x=y
         */
        static <T> java.util.function.Function<T, T> identity() {
            return t -> t;
        }
    }

Function示例

定义一个学生类Student,它有name和score两个属性,如下所示。

@Setter
@Getter
public class Student {

    String name;

    double score;

    public Student(String name, double score) {
        this.name = name;
        this.score = score;
    }
}

 列表处理的一个常见需求是转换。比如,给定一个学生列表,需要返回名称列表,或者将名称转换为大写返回,可以借助Function写一个通用的方法,如下所示:

public static <T, R> List<R> map(List<T> list, Function<T, R> mapper) {
    List<R> retList = new ArrayList<>(list.size());
    for (T e : list) {
        retList.add(mapper.apply(e));
    }
    return retList;
}
public static void main(String[] args) {

    List<Student> students = Arrays.asList(new Student[]{
            new Student("zhangsan", 80d),
            new Student("lisi", 89d),
            new Student("wangwu", 98d)});

    // 将学生名称转换为大写的代码为:
    Function<Student, Student> function = t -> new Student(t.getName().toUpperCase(), t.getScore());
    List<Student> students_1 = map(students, function);
    System.out.println("students_1:" + students_1.toString());

    // 根据学生列表返回分数列表的代码为:
    Function<Student, Double> function2 = t -> t.getScore();
    List<Double> scores = map(students, function2);
    System.out.println("scores:" + scores.toString());

    // andThen 示例
    Function<Student, Double> function3 = function2.andThen(x -> x + 10);
    List<Double> scores_2 = map(students, function3);
    System.out.println("scores_2:" + scores_2.toString());

}

 

posted @ 2020-09-18 14:36  草木物语  阅读(199)  评论(0编辑  收藏  举报