java.util.function.Function<T,R>接口用来根据一个类型的数据得到另一个类型的数据,
前者称为前置条件,后者称为后置条件。
1. apply方法应用
Function接口中最主要的抽象方法为:R apply(T t),根据类型T的参数获取类型R的结果
package com.demo;
import java.util.function.Function;
/*
java.util.function.Function<T,R>接口用来根据一个类型的数据得到另一个类型的数据,
前者称为前置条件,后者称为后置条件。
Function接口中最主要的抽象方法为:R apply(T t),根据类型T的参数获取类型R的结果
使用的场景例如:将String类型转换为Integer类型
*/
public class FunctionApply {
/*
定义一个方法
方法的参数传递一个字符串类型的整数
方法的参数传递一个Function接口,泛型使用<String,Integer>
使用Function接口中的方法apply,把字符串类型的整数,转换为Integer类型的数据
*/
public static void change(String s, Function<String,Integer> fun){
int in = fun.apply(s); //自动拆箱 Integer-->int
System.out.println(in);
}
public static void main(String[] args) {
//定义一个字符串类型的整数
String s = "123";
//调用change方法,传递字符串类型的整数,和Lambda表达式
change(s,(String str)->{
//把字符串类型的整数,转换为Integer类型的数据
return Integer.parseInt(str);
});
//优化Lambda
change(s, str-> Integer.parseInt(str));
}
}
2. andThen方法应用
package com.demo;
import java.util.function.Function;
/*
Function接口中的默认方法andThen:用来进行组合操作
使用andThen方法,把两次转换组合在一起使用
String s = fun1.andThen(fun2).apply("123");
fun1先调用apply方法,把字符串转换为Integer
fun2再调用apply方法,把Integer转换为字符串
*/
public class FunctionAndThen {
/*
定义一个方法
参数传递一个字符串类型的整数
参数再传递两个Function接口
一个泛型使用Function<String,Integer>
一个泛型使用Function<Integer,String>
*/
public static void change(String s, Function<String, Integer> fun1,
Function<Integer, String> fun2) {
String ss = fun1.andThen(fun2).apply(s);
System.out.println(ss);
}
public static void main(String[] args) {
//定义一个字符串的整数
String s = "123";
//调用change方法,传递字符串和两个Lambda表达式
change(s, (String str) -> {
//把字符串转换为整数+10
return Integer.parseInt(str) + 10;
}, (Integer i) -> {
//把整数转换为字符串
return i + "";
});
//优化Lambda表达式
change(s, str -> Integer.parseInt(str) + 10, i -> i + "");
}
}
以上代码注释已经说得很详细了,总体上来说,函数式编程熟悉了以后,代码是简洁了。但是在实际应用时,还需要考虑代码的易读性和易调试性。