Function应用
Interface Function<T,R>
参数类型
T
- 函数输入的类型
R
- 函数的结果类型
可用lambda表达式或重写Apply方法实现Function。
实现一个Function
主要重写Apply方法,一般使用lambda表达式。
低端写法:
@Test
void testFunction01() {
Function<Long,Integer> function = new Function<Long, Integer>() {
@Override
public Integer apply(Long aLong) {
return Integer.valueOf(aLong.toString());
}
};
Long zz = 2L;
Integer cc = function.apply(zz);
System.out.println(cc);
}
Lambda 之低端写法
@Test
void testFunction() {
Function<Long,Integer> function = (u) -> {
return Integer.valueOf(u.toString());
};
Long zz = 2L;
Integer cc = function.apply(zz);
System.out.println(cc);
}
Lambda 表达式:
@Test
void testFunction() {
Function<Long,Integer> function = u -> Integer.valueOf(u.toString());
Long zz = 2L;
Integer cc = function.apply(zz);
System.out.println(cc);
}
功能方法
Modifier and Type | Method and Description |
---|---|
default Function | andThen(Function after) 返回一个组合函数,首先将该函数应用于其输入,然后将 after 函数应用于结果。 |
R | apply(T t) 将此函数应用于给定的参数。 |
default Function | compose(Function before) 返回一个组合函数,首先将 before 函数应用于其输入,然后将此函数应用于结果。 |
static Function | identity() 返回一个总是返回其输入参数的函数。 |
apply执行函数
R apply(T t)
将参数t应用于此Function,并返回结果R
andThen组合函数
Function andThen(Function after)
default <V> Function<T,V> andThen(Function<? super R,? extends V> after)
给指定Function添加组合函数,添加的组合函数会后执行;
返回组装好的组合函数
异常
NullPointerException
- 如果after为null
compose组合函数
Function compose(Function before)
default <V> Function<V,R> compose(Function<? super V,? extends T> before)
给指定Function添加组合函数,添加的组合函数会先执行;
返回组装好的组合函数
异常
NullPointerException
- 如果before是空
identity静态方法
static <T> Function<T,T> identity()
返回一个总是返回其输入参数的函数。
-
参数类型
T
- 函数的输入和输出对象的类型 -
结果
一个总是返回其输入参数的函数
@Test
void testFunction() {
Function<String,Long> beforeFunction = text -> Long.valueOf(text);
Function<Long,Integer> function = aLong -> Integer.valueOf(aLong.toString());
Function<Integer,Double> afterFunction = text -> Double.valueOf(text);
String textBefore = "100";
Long longAfter = 100L;
//function组合beforeFunction函数,并返回新函数,注意参数类型书写正确
Function<String,Integer> composeFunction = function.compose(beforeFunction);
//function组合afterFunction函数,并返回新函数,注意参数类型书写正确
Function<Long,Double> andThenFunction = function.andThen(afterFunction);
Integer applyBefore = composeFunction.apply(textBefore);
Double applyAfter = andThenFunction.apply(longAfter);
Function<String,String> identityFunction = Function.identity();
identityFunction.apply("这是一个不变的结果");
System.out.println(identityFunction.apply("这是一个不变的结果"));
}
基于双冒号的应用
PeopleTypeCountBO::getAllCount
双冒号实际是一个实现了getAllCount()方法的Function。
Function<PeopleTypeCountBO, Integer> function = PeopleTypeCountBO::getAllCount;
Function<PeopleTypeCountBO, Integer> functionGetAllCount = peopleTypeCountBO1 -> peopleTypeCountBO1.getAllCount();
//以下二者结果相同
function.apply(peopleTypeCountBO);
functionGetAllCount.apply(peopleTypeCountBO);