Function 根据提供的值以及提供的函数返回新的值。Functional Method是apply。
/*** Applies this function to the given argument.** @param t the function argument* @return the function result*/R apply(T t);
compose方法用来结合两个Function函数,先运行的是before
/*** Returns a composed function that first applies the {@code before}* function to its input, and then applies this function to the result.* If evaluation of either function throws an exception, it is relayed to* the caller of the composed function.** @param <V> the type of input to the {@code before} function, and to the* composed function* @param before the function to apply before this function is applied* @return a composed function that first applies the {@code before}* function and then applies this function* @throws NullPointerException if before is null** @see #andThen(Function)*/default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {Objects.requireNonNull(before);return (V v) -> apply(before.apply(v));}
andThen方法与compose相反,先执行本函数在执行after函数
/*** Returns a composed function that first applies this function to* its input, and then applies the {@code after} function to the result.* If evaluation of either function throws an exception, it is relayed to* the caller of the composed function.** @param <V> the type of output of the {@code after} function, and of the* composed function* @param after the function to apply after this function is applied* @return a composed function that first applies this function and then* applies the {@code after} function* @throws NullPointerException if after is null** @see #compose(Function)*/default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {Objects.requireNonNull(after);return (T t) -> after.apply(apply(t));}
identity输出输入
/*** 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;}
Function Fi在流中的应用:
- Stream中的map、flatMap
- Stream中map、flatMap的其他数据类型变种
@Testpublic void functionFi () {Function<String,String> revertFunction = new Function<String, String>() {@Overridepublic String apply (String o) {return StringUtils.reverse(o);}};List<String> strList = Arrays.asList("john", "xiaohundun", "sam", "joe", "gg");strList.stream().map(String::toUpperCase).map(revertFunction).forEach(System.out::println);Function<String,String> composeFunction = revertFunction.compose(new Function<Object, String>() {@Overridepublic String apply (Object o) {return ((String) o).toUpperCase();}});System.out.println("##########");strList.stream().map(composeFunction).forEach(System.out::println);System.out.println("##########");strList.stream().map(Function.identity()).forEach(System.out::println);}
虚区:
NHOJNUDNUHOAIXMASEOJGG##########NHOJNUDNUHOAIXMASEOJGG##########johnxiaohundunsamjoegg
Function Fi在非流中的应用:
- javafx的很多类中
- Map中的computeIfAbsent
- Optional中
