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 Stream流

    详解JAVA Stream流

    这篇文章主要介绍了JAVA Stream流的相关资料,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下
    2020-07-07
  • java对象转化成String类型的四种方法小结

    java对象转化成String类型的四种方法小结

    在java项目的实际开发和应用中,常常需要用到将对象转为String这一基本功能。本文就详细的介绍几种方法,感兴趣的可以了解一下
    2021-08-08
  • IDEA 配置 JRebel 热部署的方法(推荐)

    IDEA 配置 JRebel 热部署的方法(推荐)

    这篇文章主要介绍了IDEA 配置 JRebel 热部署的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-01-01
  • 深入理解Maven的坐标与依赖

    深入理解Maven的坐标与依赖

    这篇文章主要介绍了深入理解Maven的坐标与依赖,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-01-01
  • Java数据结构之顺序表的实现

    Java数据结构之顺序表的实现

    线性表(linear list)是n个具有相同特性的数据元素的有限序列。顺序表是常见的线性表之一,本文将详细讲讲顺序表的原理与实现,需要的可以参考一下
    2022-08-08
  • idea如何将指定目录打成jar包

    idea如何将指定目录打成jar包

    这篇文章主要介绍了idea如何将指定目录打成jar包问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-09-09
  • SpringBoot整合ES解析搜索返回字段问题

    SpringBoot整合ES解析搜索返回字段问题

    这篇文章主要介绍了SpringBoot整合ES解析搜索返回字段问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-03-03
  • java利用SMB读取远程文件的方法

    java利用SMB读取远程文件的方法

    这篇文章主要为大家详细介绍了java利用SMB读取远程文件的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-05-05
  • Java对象转换的实现方式汇总

    Java对象转换的实现方式汇总

    这篇文章主要介绍了Java对象转换的多种实现方式,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2025-04-04
  • Springboot @Transactional大事务处理的几点建议

    Springboot @Transactional大事务处理的几点建议

    本文主要介绍了大事务的概念及其危害,并提出了几种解决大事务问题的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2025-01-01

最新评论