函数式接口

Consumer

Consumer是一个函数式编程接口; 顾名思义,Consumer的意思就是消费,即针对某个东西我们来使用它,因此它包含有一个有输入而无输出的accept接口方法;
除accept方法,它还包含有andThen这个方法,用于串联方法顺序单条语句执行多个方法

Example

  1. public static void main(String[] args) {
  2. Consumer f = e -> System.out.println(e + "-F");
  3. Consumer f2 = e -> System.out.println(e + "-F2");
  4. //执行完F后再执行F2的Accept方法
  5. f.andThen(f2).accept("test");
  6. System.out.println("\n");
  7. //连续执行F的Accept方法
  8. f.andThen(f).andThen(f).andThen(f).accept("test1");
  9. }
  10. // 输出
  11. test-F
  12. test-F2
  13. test1-F
  14. test1-F
  15. test1-F
  16. test1-F

Function

Function也是一个函数式编程接口。它代表的含义是“函数”,而函数经常是有输入输出的,因此它含有一个apply方法,包含一个输入与一个输出。
除apply方法外,它还有compose与andThen及indentity三个方法,用法较简单

Example

基础用法

  1. private static void testFunction() {
  2. Function<Integer, Integer> f = s -> s++;
  3. Function<Integer, Integer> g = s -> s * 2;
  4. /**
  5. * 下面表示在执行F时,先执行G,并且执行F时使用G的输出当作输入。
  6. * 相当于以下代码:
  7. * Integer a = g.apply(1);
  8. * System.out.println(f.apply(a));
  9. */
  10. System.out.println(f.compose(g).apply(1));
  11. /**
  12. * 表示执行F的Apply后使用其返回的值当作输入再执行G的Apply;
  13. * 相当于以下代码
  14. * Integer a = f.apply(1);
  15. * System.out.println(g.apply(a));
  16. */
  17. System.out.println(f.andThen(g).apply(1));
  18. /**
  19. * identity方法会返回一个不进行任何处理的Function,即输出与输入值相等;
  20. */
  21. System.out.println(Function.identity().apply("a"));
  22. }

分页数据类型转换

  1. /**
  2. * PageInfo<> 分页数据类型转换
  3. * @param s
  4. * @param fun
  5. * @param <T> 分页数据源类型
  6. * @param <E> 分页数据目标类型
  7. * @return
  8. */
  9. public static <T, E> PageInfo<E> convertType(PageInfo<T> s, Function<T, E> fun) {
  10. PageInfo pageInfo = new PageInfo();
  11. BeanUtils.copyProperties(s, pageInfo);
  12. if (s.getList() == null) {
  13. return pageInfo;
  14. }
  15. List<E> responseList = s.getList().stream().map(e -> fun.apply(e)).collect(Collectors.toList());
  16. pageInfo.setList(responseList);
  17. return pageInfo;
  18. }
  19. /**
  20. * PageInfo<DevJobHistory> 转换成为 PageInfo<JobHistoryResponse>
  21. */
  22. public static void main(String[] args) {
  23. PageInfo<DevJobHistory> pageInfo = ...;
  24. PageInfo<JobHistoryResponse> pageResponse = PageUtil.convertType(pageInfo, e -> {
  25. JobHistoryResponse response = new JobHistoryResponse();
  26. BeanUtils.copyProperties(e, response);
  27. response.setJobName(jobInfo.getName());
  28. response.setBusinessLogsUrl(jobHistoryService.getBusinessLogUrl(e.getApplicationId(), e.getFinalStatus(), e.getState()));
  29. return response;
  30. });
  31. }

Predicate

参考

【1】:https://blog.csdn.net/icarusliu/article/details/79495534