1 介绍
2 示例
2.1 调用内部类中的实现代码
/**
* apply 调用内部类中的实现代码
* @param value
* @param function
* @return
*/
public static Integer convert(String value, Function<String, Integer> function) {
return function.apply(value);
}
@Test
public void functionTest(){
String value = "2021";
Integer result = convert(value, (s) -> Integer.parseInt(s) + 222);
System.out.println(result);
}
结果
2243
2.2 内部类方式
@Test
public void functionTest2(){
// 复杂计算,镶嵌串行使用
// Function <T>:input参数 <R>:output参数
Function<Integer, Integer> function1 =x ->x+1;
// compose 源码执行
Integer result2 = function1.apply(function2.apply(2021));
System.out.println(result2);
// (V v) -> apply(before.apply(v))
Function<Integer, Integer> result3 = function1.compose(function2);
System.out.println(result3.apply(2021));
}
结果
2023
2023
2.3 多条件
@Test
public void functionTest3(){
Function<Integer, Integer> function1 =x ->x+1;
Function<Integer, Integer> result3 = function1.compose(function2);
// 多条件,拼接更多的计算
// (T t) -> after.apply(apply(t))
System.out.println(result3.andThen(function1).apply(1000));
// 返回默认参数
System.out.println(Function.identity().apply(10));
}
1003
10
2.4 实例学生对象
/**
* 实例学生对象
* @param student
* @param function
* @return
*/
public static List<Student> convertStudent(Student student, Function<Student,
List<Student>> function) {
return function.apply(student);
}
@Test
public void functionTest4(){
// 添加武士
List<Student> students = new ArrayList<>();
students.add(new Student(1, "张三", "男"));
students.add(new Student(2, "李四", "女"));
Student student=new Student(5,"武士","男");
convertStudent(student, s->{
if("武士".equals(s.getName())) {
students.add(s);
}
return students;
});
System.out.println(students);
}
结果
[Student{id=1, name='张三', sex='男'}, Student{id=2, name='李四', sex='女'}, Student{id=5, name='武士', sex='男'}]