标签:Function return 函数 接口 Integer apply public String
Function接口
Function接口在java中主要用来转换类型
通过调用apply方法将T类型转换为R类型
抽象方法:apply
R apply(T var1);
代码样例
public class Main {
public static void main(String[] args) {
String str = "13523";
Integer i = test(str, (t) -> {
return Integer.parseInt(str);
});
System.out.println("i的value: " + i);
}
public static <T, R> R test(T t, Function<T, R> f) {
return f.apply(t);
}
}
输出结果
i的value: 13523
default方法:andThen
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (t) -> {
return after.apply(this.apply(t));
};
}
代码样例
public class Main {
public static void main(String[] args) {
Function<String, Integer> f1 = (t) -> {
return Integer.parseInt(t);
};
Function<Integer, String> f2 = (t) -> {
return String.valueOf(t);
};
String str = "13523";
String str1 = test(str, f1.andThen(f2));
System.out.println("str1的value: " + str1);
}
public static <T, R> R test(T t, Function<T, R> f) {
return f.apply(t);
}
}
输出结果
str1的value: 13523
String -> Integer -> String
default方法:compose
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (v) -> {
return this.apply(before.apply(v));
};
}
与andThen刚好相反,先根据入参Function执行类型转换,然后再根据当前Function执行类型转换。
代码样例
public class Main {
public static void main(String[] args) {
Function<String, Integer> f1 = (t) -> {
return Integer.parseInt(t);
};
Function<Integer, String> f2 = (t) -> {
return String.valueOf(t);
};
Integer i = 13523;
Integer i1 = test(i, f1.compose(f2));
System.out.println("i1的value: " + i1);
}
public static <T, R> R test(T t, Function<T, R> f) {
return f.apply(t);
}
}
输出结果
i1的value: 13523
Integer -> String -> Integer
其他方法
static <T> Function<T, T> identity() {
return (t) -> {
return t;
};
}
- identity:返回一个和输入类型相同的输出类型。
标签:Function,return,函数,接口,Integer,apply,public,String 来源: https://www.cnblogs.com/buzuweiqi/p/16585935.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。