1

Function<T, R> 是 Java 8 中的一个函数式接口,用于表示接受一个输入参数 T,并返回一个结果 R 的函数。Function接口中有一个抽象方法apply,用于定义函数的逻辑。Function接口通常用于将数据进行转换、映射或者执行某种转换操作。


一、下面是 Function<T, R> 接口的简单用法示例:

import java.util.function.Function;

public class FunctionExample1 {
    public static void main(String[] args) {
        // 示例1:将字符串转换为对应的整数
        Function<String, Integer> strToInt = Integer::parseInt;
        int num = strToInt.apply("123");
        System.out.println(num); // 输出: 123

        // 示例2:将字符串转换为其长度
        Function<String, Integer> strLength = String::length;
        int length = strLength.apply("Hello World");
        System.out.println(length); // 输出: 11

        // 示例3:组合多个函数
        Function<String, Integer> strToIntAndMultiplyBy2 = strToInt.andThen(n -> n * 2);
        int result = strToIntAndMultiplyBy2.apply("5");
        System.out.println(result); // 输出: 10
    }
}

  • 在示例1中,我们创建了一个 Function<String, Integer> 对象 strToInt,将其定义为 Integer::parseInt 方法的引用。该 Function 实例可以将传入的字符串解析为相应的整数。通过调用 apply 方法,并将字符串 "123" 作为参数传入,我们可以得到整数结果 123。
  • 在示例2中,我们创建了一个 Function<String, Integer> 对象 strLength,将其定义为 String::length 方法的引用。该 Function 实例可以返回传入字符串的长度。通过调用 apply 方法,并将字符串 "Hello World" 作为参数传入,我们可以得到字符串的长度 11。
  • 在示例3中,我们将两个函数 strToInt 和 n -> n * 2 进行组合。首先将字符串转换为整数,然后将结果乘以2。通过调用 andThen 方法,我们可以得到一个新的 Function 对象 strToIntAndMultiplyBy2,它将传入的字符串转换为整数并乘以2。最终,通过调用 apply 方法,并将字符串 "5" 作为参数传入,我们可以得到结果 10。


二、Function接口可以作为方法的参数或返回值,用于将函数作为参数传递或作为结果返回

import java.util.Arrays;
import java.util.List;
import java.util.function.Function;

public class FunctionExample2 {
    public static void main(String[] args) {
        // 示例1:将Function作为方法参数
        int result1 = calculate(5, num -> num * 2);
        System.out.println(result1); // 输出:10

        // 示例2:将Function作为方法返回值
        Function<Integer, Integer> multiplier = getMultiplier();
        int result2 = multiplier.apply(5);
        System.out.println(result2); // 输出:8

        // 示例3:使用Function接口作为方法参数或返回值
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
        Function<Integer, String> intToString2 = (num) -> String.valueOf(num);

        processList(numbers, intToString2); // 将整数列表转换为字符串并打印出来
    }

    // 方法接受一个整数和一个Function作为参数,将整数应用到Function上并返回结果
    public static int calculate(int num, Function<Integer, Integer> operation) {
        return operation.apply(num);
    }

    // 方法返回一个Function,用于将整数加上固定值
    public static Function<Integer, Integer> getMultiplier() {
        int multiplierValue = 3;
        return num -> num + multiplierValue;
    }

    // 方法接受一个整数列表和一个将整数转换为字符串的函数作为参数
    // 它遍历整数列表,对每个整数应用传入的函数,将结果打印出来
    public static void processList(List<Integer> list, Function<Integer, String> processor) {
        for (Integer num : list) {
            String result = processor.apply(num);
            System.out.println(result);
        }
    }
}

  • 在示例1中,我们定义了一个calculate方法,它接受一个整数和一个Function<Integer, Integer>作为参数。方法内部将整数应用到传递的函数上,并返回结果。在main方法中,我们调用calculate方法,并传递了一个函数 (num -> num * 2),它将传入的整数乘以2。最后,我们打印输出结果。
  • 在示例2中,我们定义了一个getMultiplier方法,它返回一个Function<Integer, Integer>。该函数将传入的整数加上一个固定值 multiplierValue,这个值在方法内部定义。在main方法中,我们调用getMultiplier方法获取一个函数对象,并将整数 5 应用到该函数上,得到结果 8。
  • 在示例3中,整数列表 numbers 包含了 [1, 2, 3, 4, 5]。intToString 是一个将整数转换为字符串的函数。通过调用 processList(numbers, intToString),整数列表中的每个整数都会被转换为字符串,并打印出来


三、如何使用Function接口进行数据实体的属性映射?

import java.util.function.Function;

public class Main {
    public static void main(String[] args) {
        // 定义源实体类
        class SourceEntity {
            private String name;
            private int age;

            public SourceEntity(String name, int age) {
                this.name = name;
                this.age = age;
            }

            public String getName() {
                return name;
            }

            public int getAge() {
                return age;
            }
        }

        // 定义目标实体类
        class TargetEntity {
            private String fullName;
            private int yearOfBirth;

            public TargetEntity(String fullName, int yearOfBirth) {
                this.fullName = fullName;
                this.yearOfBirth = yearOfBirth;
            }

            public String getFullName() {
                return fullName;
            }

            public int getYearOfBirth() {
                return yearOfBirth;
            }
        }

        // 定义映射函数
        Function<SourceEntity, String> mapName = SourceEntity::getName;
        Function<SourceEntity, Integer> mapAge = SourceEntity::getAge;

        // 定义属性映射
        Function<SourceEntity, TargetEntity> mapEntity = source -> new TargetEntity(
                mapName.apply(source),
                2021 - mapAge.apply(source)
        );

        // 测试映射
        SourceEntity source = new SourceEntity("John", 30);
        TargetEntity target = mapEntity.apply(source);
        System.out.println(target.getFullName()); // 输出: John
        System.out.println(target.getYearOfBirth()); // 输出: 1991
    }
}

  • 在该示例中,定义了两个实体类:SourceEntity和TargetEntity。SourceEntity包含了name和age属性,而TargetEntity包含了fullName和yearOfBirth属性。
  • 然后,定义了两个Function接口:mapName和mapAge,它们分别将SourceEntity对象映射到其对应的属性值。
  • 接下来,定义了一个属性映射的Function接口mapEntity,它将SourceEntity映射到TargetEntity。在这个映射函数中,使用mapName和mapAge函数来获取SourceEntity的属性值,并将其传递给TargetEntity的构造函数来创建一个新的TargetEntity对象。
  • 最后,创建一个SourceEntity对象source,并将其应用于属性映射的mapEntity函数,得到一个新的TargetEntity对象target。通过访问target的属性来验证映射结果,并将其打印出来。


四、Function接口还提供了一些常用的方法来组合和转换函数,以下是Function接口的常用方法:

import java.util.function.Function;

public class FunctionExample3 {
    public static void main(String[] args) {
        Function<Integer, Integer> multiplyByTwo = x -> x * 2;
        Function<Integer, Integer> addThree = x -> x + 3;

        // 使用andThen方法组合函数
        Function<Integer, Integer> combinedFunction = multiplyByTwo.andThen(addThree);
        int result1 = combinedFunction.apply(5); // 返回 13
        System.out.println(result1);

        // 使用compose方法组合函数
        Function<Integer, Integer> composedFunction = addThree.compose(multiplyByTwo);
        int result2 = composedFunction.apply(5); // 返回 13
        System.out.println(result2);

        // 使用identity方法
        Function<Integer, Integer> identityFunction = Function.identity();
        int result3 = identityFunction.apply(5); // 返回 5
        System.out.println(result3);
    }
}

  • apply(T t):对给定的输入值应用函数,并返回结果。
  • andThen(Function<? super R, ? extends V> after):返回一个组合函数,首先将当前函数应用于输入,然后将结果应用于指定的函数。
  • compose(Function<? super V, ? extends T> before):返回一个组合函数,首先将指定的函数应用于输入,然后将结果应用于当前函数。
  • identity():返回一个函数,它总是返回其输入值。

今夜有点儿凉
40 声望3 粉丝

今夜有点儿凉,乌云遮住了月亮。