函数式接口
Consumer
Consumer是一个函数式编程接口; 顾名思义,Consumer的意思就是消费,即针对某个东西我们来使用它,因此它包含有一个有输入而无输出的accept接口方法;
除accept方法,它还包含有andThen这个方法,用于串联方法顺序单条语句执行多个方法
Example
public static void main(String[] args) {Consumer f = e -> System.out.println(e + "-F");Consumer f2 = e -> System.out.println(e + "-F2");//执行完F后再执行F2的Accept方法f.andThen(f2).accept("test");System.out.println("\n");//连续执行F的Accept方法f.andThen(f).andThen(f).andThen(f).accept("test1");}// 输出test-Ftest-F2test1-Ftest1-Ftest1-Ftest1-F
Function
Function也是一个函数式编程接口。它代表的含义是“函数”,而函数经常是有输入输出的,因此它含有一个apply方法,包含一个输入与一个输出。
除apply方法外,它还有compose与andThen及indentity三个方法,用法较简单
Example
基础用法
private static void testFunction() {Function<Integer, Integer> f = s -> s++;Function<Integer, Integer> g = s -> s * 2;/*** 下面表示在执行F时,先执行G,并且执行F时使用G的输出当作输入。* 相当于以下代码:* Integer a = g.apply(1);* System.out.println(f.apply(a));*/System.out.println(f.compose(g).apply(1));/*** 表示执行F的Apply后使用其返回的值当作输入再执行G的Apply;* 相当于以下代码* Integer a = f.apply(1);* System.out.println(g.apply(a));*/System.out.println(f.andThen(g).apply(1));/*** identity方法会返回一个不进行任何处理的Function,即输出与输入值相等;*/System.out.println(Function.identity().apply("a"));}
分页数据类型转换
/*** PageInfo<> 分页数据类型转换* @param s* @param fun* @param <T> 分页数据源类型* @param <E> 分页数据目标类型* @return*/public static <T, E> PageInfo<E> convertType(PageInfo<T> s, Function<T, E> fun) {PageInfo pageInfo = new PageInfo();BeanUtils.copyProperties(s, pageInfo);if (s.getList() == null) {return pageInfo;}List<E> responseList = s.getList().stream().map(e -> fun.apply(e)).collect(Collectors.toList());pageInfo.setList(responseList);return pageInfo;}/*** PageInfo<DevJobHistory> 转换成为 PageInfo<JobHistoryResponse>*/public static void main(String[] args) {PageInfo<DevJobHistory> pageInfo = ...;PageInfo<JobHistoryResponse> pageResponse = PageUtil.convertType(pageInfo, e -> {JobHistoryResponse response = new JobHistoryResponse();BeanUtils.copyProperties(e, response);response.setJobName(jobInfo.getName());response.setBusinessLogsUrl(jobHistoryService.getBusinessLogUrl(e.getApplicationId(), e.getFinalStatus(), e.getState()));return response;});}
Predicate
参考
【1】:https://blog.csdn.net/icarusliu/article/details/79495534
