概述

java.util.function.Function<T,R> 接口用来根据一个类型的数据得到另一个类型的数据,前者称为前置条件,后者称为后置条件。

1
2
3
4
5
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
......
}

抽象方法:apply

Function 接口中最主要的抽象方法为: R apply(T t) ,根据类型T的参数获取类型R的结果。 使用的场景例如:将 String 类型转换为 Integer 类型。

1
2
3
4
5
6
7
8
9
10
11
12
13
import java.util.function.Function;

public class DemoFunctionApply {

public static void main(String[] args) {
method(s -> Integer.parseInt(s));
}

private static void method(Function<String, Integer> function) {
int num = function.apply("10");
System.out.println(num + 20); // 30
}
}

默认方法:andThen

Function 接口中有一个默认的 andThen 方法,用来进行组合操作。JDK源代码如:

1
2
3
4
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}

该方法同样用于“先做什么,再做什么”的场景,和 Consumer 中的 andThen 差不多:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.function.Function;

public class DemoFunctionAndThen {

public static void main(String[] args) {
method(
str -> Integer.parseInt(str)+10,
i -> i *= 10
);
}

private static void method(Function<String, Integer> one, Function<Integer, Integer> two) {
int num = one.andThen(two).apply("10");
System.out.println(num + 20); // 220
}
}

应用示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.util.function.Function;

public class DemoFunction {

public static void main(String[] args) {
String str = "赵丽颖,20";

int age = getAgeNum(
str,
s -> s.split(",")[1],
s -> Integer.parseInt(s),
n -> n += 100
);
System.out.println(age);
}

private static int getAgeNum(String str,
Function<String, String> one,
Function<String, Integer> two,
Function<Integer, Integer> three) {
return one.andThen(two).andThen(three).apply(str);
}
}