Java中Function的使用及说明

 更新时间:2023年05月31日 09:33:38   作者:华妃  
这篇文章主要介绍了Java中Function的使用及说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

Java Function的使用

一、方法介绍

表示接受一个参数并产生结果的函数。

参数类型

  • T - 函数输入的类型
  • R - 函数的结果类型

方法介绍

R apply(T t)

将此函数应用于给定的参数。

default Function<V, R> compose(Function<? super V, ? extends T> before)

返回一个组合函数,首先将before函数应用于其输入,然后将此函数应用于结果。 如果任一函数的评估引发异常,则将其转发给组合函数的调用者。

default Function<T, V> andThen(Function<? super R, ? extends V> after)

返回一个组合函数,首先将此函数应用于其输入,然后将after函数应用于结果。 如果任一函数的评估引发异常,则将其转发给组合函数的调用者。

static Function<T, T> identity()

返回一个总是返回其输入参数的函数。

源码

@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 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));
    }
    /**
     * 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));
    }
    /**
     * 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;
    }
}

二、demo

public class Test {
    public static void main(String[] args) throws Exception {
        Function<Integer, Integer> add = p -> p + 10;
        Integer result = add.apply(10);
        // 这里会输出 20,因为这个函数定义的操作时把参数加上 10 后返回
        System.out.println(result);
        Function<Integer, Integer> multiplyTen = a -> a * 10;
        Function<Integer, Integer> addTen = a -> a + 10;
        // 先增加 10,然后再乘 10,输出结果 110
        Function<Integer, Integer> addTenThenMultiplyTen = multiplyTen.compose(addTen);
        System.out.println(addTenThenMultiplyTen.apply(1));
        // 先乘 10,然后再加 10,输出结果 20
        Function<Integer, Integer> multiplyTenAddTenThen = multiplyTen.andThen(addTen);
        System.out.println(multiplyTenAddTenThen.apply(1));
    }
}

结果

Java内置函数 Function函数

Java内置Function参数,类包是在 java.base 模块下 java.util.function 包中,其方法主要用于对一个请求参数的处理,并返回一个结果。

Function源码

package java.util.function;
import java.util.Objects;
/**
 * Represents a function that accepts one argument and produces a result.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #apply(Object)}.
 *
 * @param <T> the type of the input to the function
 * @param <R> the type of the result of the function
 *
 * @since 1.8
 */
@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 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));
    }
    /**
     * 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));
    }
    /**
     * 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主要方法

apply方法

当前方法就是我们使用匿名函数时需要重写的方法,其中请求参数和返回参数都需要在我们生成Function对象的时候传进去,而apply方法也是这个类最核心的方法。

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

创建 简单的Function对象

Function是现有43个函数中基础的函数之一,简单的方法可以省略方法体{},和if的写法一样,但是复杂写法不可以省略{}。

/**
	 * ([参数列表]) ->{
 	 * 	代码体;
 	 * }
 	 * 或
	 * ([参数列表]) ->代码体
	 *
	 */
    public static void main(String[] args) {
        //Function<T, R> 传入一个参数,并返回一个参数,两个参数类型需要自己传 可以对数据进行处理
        Function<String,Integer> stringIntegerAddFunction=(str)->Integer.parseInt(str)+1;
        System.out.println(stringIntegerAddFunction.apply("100"));
        Function<String,Integer> stringIntegerAddFunction2=(str)->{
            Integer integer=Integer.parseInt(str);
            return integer+1;
        };
        System.out.println(stringIntegerAddFunction2.apply("100"));
    }

两个写法虽然不一致,但是执行的结果是一样的。

简单Funciton对象的返回结果

compose方法、andThen方法和identity方法

使用匿名函数时,匿名函数接口的类中只允许存在一个方法,而之所有这三方法,是因为接口中可以通过关键字default定义默认方法,实现类如果不想要默认方法的实现逻辑可以根据需求重新定义,通过关键字static定义静态方法,实现类如果不想要静态方法的实现逻辑可以根据需求重新定义。

compose方法

有的时候,我们需要将两个或多个方法进行组合使用,这个时候就需要compose方法,compose会通过从右到左的顺序执行我们拼接的方法。

/**
	 * ([参数列表]) ->{
 	 * 	代码体;
 	 * }
 	 * 或
	 * ([参数列表]) ->代码体
	 *
	 */
 public static void main(String[] args) {
        //Function<T, R> 传入一个参数,并返回一个参数,两个参数类型需要自己传 可以对数据进行处理
        Function<String,Integer> stringIntegerAddFunction=(str)->Integer.parseInt(str)+1;
        Function<Integer,String> integerStringFunction=integer -> String.valueOf(integer*2);
        System.out.println(stringIntegerAddFunction.compose(integerStringFunction).apply(100));
    }

可以通过结果看出,compose拼接会先执行被拼接的函数(integerStringFunction),再回去调用我们拼接的函数(stringIntegerAddFunction),为方便查看,我们请求的apply方法的类型已经发送了改变。

使用compose方法返回结果

andThen方法

andThen方法则刚好相反,这个函数会把拼接的函数从左到右执行。

/**
	 * ([参数列表]) ->{
 	 * 	代码体;
 	 * }
 	 * 或
	 * ([参数列表]) ->代码体
	 *
	 */
    public static void main(String[] args) {
        //Function<T, R> 传入一个参数,并返回一个参数,两个参数类型需要自己传 可以对数据进行处理
        Function<String,Integer> stringIntegerAddFunction=(str)->Integer.parseInt(str)+1;
        Function<Integer,String> integerStringFunction=integer -> String.valueOf(integer*2);
        System.out.println(stringIntegerAddFunction.andThen(integerStringFunction).apply("100"));
    }

根据结果可以看出,andThen拼接会先执行被拼接的函数(stringIntegerAddFunction),再回去调用我们拼接的函数(integerStringFunction),为方便查看,我们请求的apply方法的类型已经发送了改变。

andThen方法返回结果

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Java 8新增的方法参数反射实例分析

    Java 8新增的方法参数反射实例分析

    这篇文章主要介绍了Java 8新增的方法参数反射,结合实例形式分析了java8新增api方法参数反射相关操作技巧,需要的朋友可以参考下
    2019-07-07
  • Java实现简单的飞机大战游戏(敌机下落篇)

    Java实现简单的飞机大战游戏(敌机下落篇)

    这篇文章主要为大家详细介绍了Java实现简单的飞机大战游戏,敌机下落篇,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-05-05
  • mybatis中resulthandler的用法

    mybatis中resulthandler的用法

    这篇文章主要介绍了mybatis中resulthandler的用法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-01-01
  • Java中锁的实现和内存语义浅析

    Java中锁的实现和内存语义浅析

    这篇文章主要给大家介绍了关于Java中锁的实现和内存语义的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2018-11-11
  • spring AOP代理执行@EnableAspectJAutoProxy的exposeProxy属性详解

    spring AOP代理执行@EnableAspectJAutoProxy的exposeProxy属性详解

    这篇文章主要为大家介绍了spring AOP代理执行@EnableAspectJAutoProxy的exposeProxy属性详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-09-09
  • Java开发学习之Bean的作用域和生命周期详解

    Java开发学习之Bean的作用域和生命周期详解

    这篇文章主要介绍了浅谈Spring中Bean的作用域,生命周期和注解,从创建到消亡的完整过程,例如人从出生到死亡的整个过程就是一个生命周期。本文将通过示例为大家详细讲讲,感兴趣的可以学习一下
    2022-06-06
  • 使用Netty解决TCP粘包和拆包问题过程详解

    使用Netty解决TCP粘包和拆包问题过程详解

    这篇文章主要介绍了使用Netty解决TCP粘包和拆包问题过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-07-07
  • Java中Properties的使用详解

    Java中Properties的使用详解

    这篇文章主要介绍了Java中Properties的使用详解的相关资料,需要的朋友可以参考下
    2016-05-05
  • 谈谈Hashmap的容量为什么是2的幂次问题

    谈谈Hashmap的容量为什么是2的幂次问题

    这篇文章主要介绍了谈谈Hashmap的容量为什么是2的幂次问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-09-09
  • RestTemplate自定义请求失败异常处理示例解析

    RestTemplate自定义请求失败异常处理示例解析

    这篇文章主要为大家介绍了RestTemplate自定义请求失败异常处理的示例解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步早日升职加薪
    2022-03-03

最新评论