1、什么是Function接口? 在java8以后的接口可以有接口方法的默认实现了,Function源代码如下:
@FunctionalInterface
public interface Function<T, R> {
//将参数赋予给相应方法,传入T,返回R
R apply(T t);
//先执行参数,再执行调用者 两个Function,先执行后面的,再执行前面的
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
//先执行调用者,再执行参数,和compose相反。先执行第一个fun1,再接着执行后面的fun2
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
//返回当前正在执行的方法
static <T> Function<T, T> identity() {
return t -> t;
}
}
2、具体使用例子代码如下:
apply方法使用,传入字符串,返回一个字符串:
/**
* apply 传入字符串,返回一个字符串
*/
public class FunctionApply {
public static void main(String[] args) {
functionApply();
}
/**
* 传入参数字符串,返回参数字符串。字符串转大小写
*/
public static void functionApply () {
String result = typeConvert("amy", String::toUpperCase);
//function --> AMY
System.out.printf("function --> {%s}%n", result);
}
/***
* Function apply接口 传入一个参数,返回值一个参数
*/
public static <R> R typeConvert (String str, Function<String, R> function) {
return function.apply(str);
}
}
andThen方法,先执行fun1,再执行fun2
/**
* andThen 先执行fun1,再执行fun2
*/
public class FunctionAndThen {
public static void main(String[] args) {
functionAndThen();
}
/**
* 先将字符串100转换未Integer类型,再Integer + 10得到结果 110
*/
public static void functionAndThen() {
Integer result = typeConvert("100", Integer::parseInt, s2 -> (s2 + 10));
//function --> 110
System.out.printf("function --> {%s}%n", result);
}
/**
* 先执行fun1,再执行fun2 传入参数str
*/
public static <R> R typeConvert(String str, Function<String, Integer> fun1, Function<Integer, R> fun2) {
return fun1.andThen(fun2).apply(str);
}
}
compose方法,先执行fun2,再执行fun1 跟andThen相反
/**
* compose 先执行fun2,再执行fun1 跟andThen相反
*/
public class FunctionCompose {
public static void main(String[] args) {
functionCompose();
}
/**
* 先执行fun2 100*100 转换为String类型 再执行fun1把String转换为BigDecimal
*/
public static void functionCompose() {
BigDecimal amount = typeConvert2(100, BigDecimal::new, s2 -> String.valueOf(s2 * s2));
//function --> 10000
System.out.printf("function --> {%s}%n", amount);
}
/**
* 传入number 先执行fun2 Integer转String 再执行fun1 String 转泛型R
*/
public static <R> R typeConvert2(Integer number, Function<String, R> fun1, Function<Integer, String> fun2) {
return fun1.compose(fun2).apply(number);
}
}
identity方法,数值为本身 s -> s 替换为 Function.identity()
/**
* identity 数值为本身 s -> s 替换为 Function.identity()
*/
public class FunctionIdentity {
public static void main(String[] args) {
identity();
}
/**
* 把List转为Map, s -> s 表示map的key值,key的数值为本身,可以简写为
*/
public static void identity() {
List<String> strings = Arrays.asList("abc", "de");
//数值为本身 Function.identity() 替换 s -> s,Collectors.toMap(s -> s, String::length));
Map<String, Integer> map = strings.stream().collect(Collectors.toMap(Function.identity(), String::length));
//function --> {de=2, abc=3}
System.out.printf("function --> {%s}%n", map);
}
}