函数式接口Function
软件包 java.util.function
Interface Function<T,R>
Function 接口用来对给定的 T 类型参数j进行,然后返回一个 R 类型的结果。
方法摘要 |
---|
返回值类型 | 方法 | 描述 |
---|---|---|
R | apply(T t) | 将此函数应用于给定的参数。 |
default Function<T,V> | andThen(Function<? super R,? extends V> after) | 返回一个组合函数,首先将该函数应用于其输入,然后将 after函数应用于结果。 |
default Function<V,R> | compose(Function<? super V,? extends T> before) | 返回一个组合函数,首先将 before函数应用于其输入,然后将此函数应用于结果。 |
static Function<T,T> | identity() | 返回一个总是返回其输入参数的函数。 |
- apply()方法:对给定参数进行处理并返回结果(多用于类型转换,将参数类型T转为参数类型R)
import java.util.function.Function;
public class FunctionDemo01 {
public static void main(String[] args) {
//使用lambda表达式实现方法
System.out.println(fun1("123", str -> Integer.valueOf(str)));
String user = "张彪,66";
//将user中的年龄取出增加 1 再转换为字符串后输出
System.out.println(appendAge(user, s -> Integer.parseInt(s.split(",")[1]) + 1,
s -> s.toString()));
}
//将字符串转换为int类型
private static Integer fun1(String str, Function<String, Integer> fun){
return fun.apply(str);
};
private static String appendAge(String str, Function<String, Integer> fun1, Function<Integer, String> fun2){
return fun1.andThen(fun2).apply(str);
}
}