public class FunctionTest {
@Test
public void test() {
// int 转 str
Function<Integer, String> int2Str = String::valueOf;
// 平方
Function<String, Integer> square = e -> {
int i = Integer.parseInt(e);
return i * i;
};
// 格式输出
Function<String, Date> format = e -> new Date();
String apply = int2Str.apply(5);
// note: apply 实际传入的参数类型取决于compose,这里前置函数需要String类型,所以传入"5"
// note: andThen 的函数入参必须是apply的return类型
Date apply2 = int2Str
.compose(square) // 前置处理: apply执行前,先计算平方
.andThen(format) // 后置处理: apply执行后,格式化输出
.apply("5"); // 处理
System.out.println(apply);
System.out.println(apply2); //
}
@Test
public void test2() {
List<String> names = List.of("Alice", "Bob", "Charlie");
// note 定义可扩展的方法,处理逻辑动态传入. 使用Function.identity()进行占位
List<String> processedNames = processList(names, Function.identity());
System.out.println(processedNames); // 输出: [Alice, Bob, Charlie]
}
public static <T> List<T> processList(List<T> list, Function<T, T> processor) {
List<T> result = new ArrayList<>();
for (T item : list) {
result.add(processor.apply(item)); // 应用处理函数
}
return result;
}
}
09-22
228
09-24
217
09-24
837