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方法返回结果

总结

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

相关文章

  • 详解maven的setting配置文件中mirror和repository的区别

    详解maven的setting配置文件中mirror和repository的区别

    这篇文章主要介绍了详解maven的setting配置文件中mirror和repository的区别,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-12-12
  • HttpClient详细使用示例代码

    HttpClient详细使用示例代码

    这篇文章主要介绍了HttpClient详细使用示例,包括导入依赖,使用工具类的详细代码,代码简单易懂,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-07-07
  • Java设计模式之桥接模式实例详解

    Java设计模式之桥接模式实例详解

    这篇文章主要介绍了Java设计模式之桥接模式,结合实例形式详细分析了桥接模式的概念、功能、Java实现方法及相关注意事项,需要的朋友可以参考下
    2017-09-09
  • SpringBoot +Vue开发考试系统的教程

    SpringBoot +Vue开发考试系统的教程

    这篇文章主要介绍了SpringBoot +Vue开发考试系统,支持多种题型:选择题、多选题、判断题、填空题、综合题以及数学公式。支持在线考试,教师在线批改试卷。本文通过实例代码给大家介绍的非常详细,需要的朋友可以参考下
    2020-05-05
  • 使用Springboot封装好的发送post请求的工具类

    使用Springboot封装好的发送post请求的工具类

    本文介绍了在Springboot中封装发送HTTP请求的工具类,并提供了普通的HTTP请求工具类代码和Response类的使用示例,这些工具类可为开发者提供便利性和参考价值,帮助提高开发效率
    2024-09-09
  • java实现翻转单词顺序列

    java实现翻转单词顺序列

    这篇文章主要为大家详细介绍了java实现翻转单词顺序列,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-03-03
  • mybaits-spring的实现方式

    mybaits-spring的实现方式

    这篇文章主要介绍了mybaits-spring的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-05-05
  • Java 入门图形用户界面设计之列表框JList

    Java 入门图形用户界面设计之列表框JList

    图形界面(简称GUI)是指采用图形方式显示的计算机操作用户界面。与早期计算机使用的命令行界面相比,图形界面对于用户来说在视觉上更易于接受,本篇精讲Java语言中关于图形用户界面的列表框JList
    2022-02-02
  • Spring拦截器和过滤器的区别在哪?

    Spring拦截器和过滤器的区别在哪?

    相信很多小伙伴都对Spring拦截器和过滤器的区别有疑惑,今天特地整理了本篇文章,文中有非常详细的介绍,需要的朋友可以参考下
    2021-06-06
  • Java中Sentinel框架详解

    Java中Sentinel框架详解

    Sentinel是一个高可用、高扩展、高稳定性的开源流量控制和熔断降级框架,可以在分布式系统中实现实时的流量控制,防止系统因流量过大导致系统崩溃和服务降级,Sentinel面向所有的Java应用,本文就给大家详细介绍一下Java中Sentinel框架,需要的朋友可以参考下
    2023-06-06

最新评论