Java函数式接口Function

Function 提供了一个抽象方法  R apply(T t) 接收一个参数 返回 一个值,还有两个默认方法和一个静态方法

compose 是一个嵌套方法,先执行before.apply() 得到运算后的值,再执行apply(),andthen则相反

identity 输入一个值则返回一个值,t -> t 实际是 apply() 这个方法的实现

 另外还有BiFunction、toIntFunction、DoubleToIntFunction 等函数式接口,区别在于参数的不同,比如LongToIntFunction 是接收一个Long参数,返回一个Int值

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;
}

 

方法示例:

arrToArrayList 是在方法体里运算,而 arrToList 则将方法作为参数传递进去

package jdk8.function;


import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Function;

public class FunctionTest {
    public static void main(String[] args) {
        Integer[] i = {1, 2, 4, 5};
        Function<Integer[], ArrayList<Integer>> arrayListFunction = FunctionTest::arrToArrayList;
        arrayListFunction.apply(i).forEach(System.out::println);

        ArrayList<Integer> list = FunctionTest.arrToList(i, l -> new ArrayList<>(Arrays.asList(l)));
        list.forEach(System.out::println);

        FunctionTest.arrToList(i, l -> new HashSet<>(Arrays.asList(l))).forEach(System.out::println);
        FunctionTest.arrToList(i, l -> new LinkedList<>(Arrays.asList(l))).forEach(System.out::println);

        FunctionTest.arrToList(i, l -> new LinkedList<>(Arrays.asList(l))).forEach(System.out::println);

        System.out.println(FunctionTest.compute(7, s -> s + ""));

        System.out.println(FunctionTest.addition("hello", "wolrd", (a, b) -> a + " " + b));
        
        Function<String,String> function = Function.identity();
        function.apply("hello wolrd");
    }

    //将数组转为ArrayList
    private static <T> ArrayList<T> arrToArrayList(T[] t) {
        Objects.requireNonNull(t);
        return new ArrayList<>(Arrays.asList(t));
    }

    private static<T,R> R arrToList(T[] t, Function<T[], R> function) {
        Objects.requireNonNull(t);
        return function.apply(t);
    }


    public static String compute(int a, Function<Integer, String> function) {
        return function.apply(a);             //function.apply() 接收实际的行为
    }

    public static String addition(String a, String b, BiFunction<String, String, String> biFunction) {
        return biFunction.apply(a, b);
    }
}
posted @ 2019-05-21 15:47  高龄码农丹  阅读(11895)  评论(0编辑  收藏  举报