先上java的闭包(利用Function和BiFunction实现)

Function

从Function的定义中可以看到,它其实是一个接口,可以接收一个泛型的输入参数,和一个泛型的返回参数,使用也很简单,可以看下面的demo

/**
 * @param num
 * @param function
 * @return
 * @desc 使用JDK8 Function函数
 */
private Integer compute(Integer num, Function<Integer, Integer> function) {
    Integer result = function.apply(num);
    return result;
}

在这里插入图片描述

但是有时候一个参数不够用啊,怎么办呢,这个时候就可以用BiFunction了

String calculatePlus(Integer num1, Integer num2, BiFunction<Integer,Integer,String> biFunction){
    //这里按照声明的BiFunction<Integer,Integer,String> 传入2个Integer类型的形参,返回一个String类型的返回值
    String result = biFunction.apply(num1,num2);
    System.out.println("闭包的返回值"+result);
    return result.concat("Hello World");
}

在这里插入图片描述

经过上面2个demo,对于闭包的初步理解以及使用逐渐清晰了,但是只有一个闭包方法还是满足不了生产环境的,这个时候Function的嵌套闭包就可以出场了

使用compose函数,简单的说,就是从右向左处理

@Test
public void contextLoads() {    

    System.out.println(
            calculatePlusPlus(2,"加班啊",(value1) -> {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("我是function1 " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + " value = " + value1);
                return value1 + value1;
            }, (value2) -> {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("我是function2 " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + " value = " + value2);
                return String.valueOf(value2 + value2);
            })
    );

}

String calculatePlusPlus(Integer num1, String str1, Function<Integer,Integer> function1, Function<Integer,String> function2){
    //这里 function2 会把 function1 返回的 Integer 类型的返回值作为输入值,然后参与 function2 自己的闭包运算,后面的那个 apply(num1) 其实是function1的输入
    String function2Result = function2.compose(function1).apply(num1);

   /* //还能这里的执行顺序的从后往前的,先执行最后的 function1 再执行 倒数第二个 function1 最后执行 function2
    //为什么呢,主要是 compose 方法里先执行的传入的参数的 apply
    String function2Result = function2.compose(function1).compose(function1).apply(num1);*/
    System.out.println("闭包的返回值" + function2Result);
    return function2Result.concat(" Hello World");
}

输出的值
在这里插入图片描述
compose方法的定义
在这里插入图片描述

当然也可以使用andThen从左向右执行的

@Test
public void contextLoads() {

    System.out.println(
            calculatePlusPlusPlus(2,"加班啊",(value1) -> {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("我是function3 " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + " value = " + value1);
                return String.valueOf(value1 + value1);
            }, (value2) -> {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("我是function4 " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + " value = " + value2);
                return value2 + value2;
            })
    );

}

/**
 * andThen 从左向右执行
 * @param num1
 * @param str1
 * @param function3
 * @param function4
 * @return
 */
String calculatePlusPlusPlus(Integer num1, String str1, Function<Integer,String> function3, Function<Integer,Integer> function4){
    //这里 function3 会把 function4 返回的 Integer 类型的返回值作为输入值,然后参与 function3 自己的闭包运算,后面的那个 apply(num1) 其实是 function4 的输入
    String function2Result = function4.andThen(function3).apply(num1);

    System.out.println("闭包的返回值" + function2Result);
    return function2Result.concat(" Hello World");
}

在这里插入图片描述

整体demo的代码

package com.felix.event;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.function.BiFunction;
import java.util.function.Function;

@SpringBootTest
public class EventApplicationTests {

    @Test
    public void contextLoads() {
        System.out.println(calculate(6,(value) ->{
            return value + value;
        }));


        System.out.println(calculatePlus(1,2,(value1,value2) -> {
            return String.valueOf(value1 * value2);
        }));

        System.out.println(
                calculatePlusPlus(2,"加班啊",(value1) -> {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("我是function1 " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + " value = " + value1);
                    return value1 + value1;
                }, (value2) -> {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("我是function2 " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + " value = " + value2);
                    return String.valueOf(value2 + value2);
                })
        );


        System.out.println(
                calculatePlusPlusPlus(2,"加班啊",(value1) -> {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("我是function3 " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + " value = " + value1);
                    return String.valueOf(value1 + value1);
                }, (value2) -> {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("我是function4 " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + " value = " + value2);
                    return value2 + value2;
                })
        );

    }

    /**
     * andThen 从左向右执行
     * @param num1
     * @param str1
     * @param function3
     * @param function4
     * @return
     */
    String calculatePlusPlusPlus(Integer num1, String str1, Function<Integer,String> function3, Function<Integer,Integer> function4){
        //这里 function3 会把 function4 返回的 Integer 类型的返回值作为输入值,然后参与 function3 自己的闭包运算,后面的那个 apply(num1) 其实是 function4 的输入
        String function2Result = function4.andThen(function3).apply(num1);

        System.out.println("闭包的返回值" + function2Result);
        return function2Result.concat(" Hello World");
    }

    /**
     * compose 从右向左执行
     * @param num1
     * @param str1
     * @param function1
     * @param function2
     * @return
     */
    String calculatePlusPlus(Integer num1, String str1, Function<Integer,Integer> function1, Function<Integer,String> function2){
        //这里 function2 会把 function1 返回的 Integer 类型的返回值作为输入值,然后参与 function2 自己的闭包运算,后面的那个 apply(num1) 其实是function1的输入
        String function2Result = function2.compose(function1).apply(num1);

       /* //还能这里的执行顺序的从后往前的,先执行最后的 function1 再执行 倒数第二个 function1 最后执行 function2
        //为什么呢,主要是 compose 方法里先执行的传入的参数的 apply
        String function2Result = function2.compose(function1).compose(function1).apply(num1);*/
        System.out.println("闭包的返回值" + function2Result);
        return function2Result.concat(" Hello World");
    }

    Integer calculate(Integer num, Function<Integer,Integer> function){
        //这里按照声明的Function<Integer,Integer> 传入1个 Integer 类型的形参,返回一个 Integer 类型的返回值
        Integer result = function.apply(num);
        System.out.println("闭包的返回值"+result);
        return result + result;
    }



    String calculatePlus(Integer num1, Integer num2, BiFunction<Integer,Integer,String> biFunction){
        //这里按照声明的BiFunction<Integer,Integer,String> 传入2个Integer类型的形参,返回一个String类型的返回值
        String result = biFunction.apply(num1,num2);
        System.out.println("闭包的返回值"+result);
        return result.concat("Hello World");
    }




}

参考自大佬的博文
https://www.cnblogs.com/webor2006/p/8204591.html

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐