• java8函数式编程,常用高阶函数处理


    jdk1.8引入了Lombda表达式,函数式编程,帮我大大减少了代码的重复性,和代码的复杂度,更优雅的处理我们代码和方法,也能帮我业务数据做处理。

    函数接口:

    函数接口指仅具有单个抽象方法的接口,用来表示 Lambda 表达式的类型。

    是惰性求值还是及早求值很简单:只需看它的返回值。如果返回值是 Stream, 那么是惰性求值;如果返回值是另一个值或为空,那么就是及早求值。

    通过构建建筑者模式构建数据:

    1. package com.example.java8.employees;
    2. import java.util.List;
    3. import java.util.Objects;
    4. /**
    5. * 使用建造者模式创建对象:
    6. * 1,对象在赋值过后进行bulider创建对象
    7. *2,多线程里面对象他是线程安全,类this指向
    8. * @author xpwi
    9. * @since 2022-08-14
    10. */
    11. public class EmployeesVO {
    12. /**
    13. * id 编号
    14. */
    15. private int id;
    16. /**
    17. * 姓名
    18. */
    19. private String name;
    20. /**
    21. * 性别
    22. */
    23. private Integer gender;
    24. /**
    25. * 年龄
    26. */
    27. private Integer age;
    28. /**
    29. * 信息
    30. */
    31. private String msg;
    32. private List result;
    33. public EmployeesVO(Bulider bulider){
    34. this.id = bulider.id;
    35. this.name = bulider.name;
    36. this.age = bulider.age;
    37. this.gender = bulider.gender;
    38. this.msg = bulider.msg;
    39. this.result=bulider.result;
    40. }
    41. public int getId() {
    42. return id;
    43. }
    44. public void setId(int id) {
    45. this.id = id;
    46. }
    47. public String getName() {
    48. return name;
    49. }
    50. public void setName(String name) {
    51. this.name = name;
    52. }
    53. public Integer getGender() {
    54. return gender;
    55. }
    56. public void setGender(Integer gender) {
    57. this.gender = gender;
    58. }
    59. public Integer getAge() {
    60. return age;
    61. }
    62. public void setAge(Integer age) {
    63. this.age = age;
    64. }
    65. public String getMsg() {
    66. return msg;
    67. }
    68. public void setMsg(String msg) {
    69. this.msg = msg;
    70. }
    71. public List getResult() {
    72. return result;
    73. }
    74. public void setResult(List result) {
    75. this.result = result;
    76. }
    77. /**
    78. * 工厂
    79. *
    80. */
    81. public static class Bulider{
    82. /**
    83. * id 编号
    84. */
    85. private int id;
    86. /**
    87. * 姓名
    88. */
    89. private String name;
    90. /**
    91. * 性别
    92. */
    93. private Integer gender;
    94. /**
    95. * 年龄
    96. */
    97. private Integer age;
    98. /**
    99. * 信息
    100. */
    101. private String msg;
    102. private List result;
    103. public Bulider(int id, String name, Integer gender, Integer age, String msg,List result) {
    104. this.id = id;
    105. this.name = name;
    106. this.gender = gender;
    107. this.age = age;
    108. this.msg = msg;
    109. this.result = result;
    110. }
    111. public Bulider id(int id){
    112. this.id=id;
    113. return this;
    114. }
    115. public Bulider name(String name){
    116. this.name=name;
    117. return this;
    118. }
    119. public Bulider name(Integer gender){
    120. this.gender=gender;
    121. return this;
    122. }
    123. public Bulider age(Integer age){
    124. this.age=gender;
    125. return this;
    126. }
    127. public Bulider age(String msg){
    128. this.msg=msg;
    129. return this;
    130. }
    131. public Bulider result(List result){
    132. this.result=result;
    133. return this;
    134. }
    135. /**
    136. * this指向赋值this
    137. * @return
    138. */
    139. public EmployeesVO bulider(){
    140. return new EmployeesVO(this);
    141. }
    142. }
    143. @Override
    144. public boolean equals(Object o) {
    145. if (this == o) return true;
    146. if (o == null || getClass() != o.getClass()) return false;
    147. EmployeesVO that = (EmployeesVO) o;
    148. return id == that.id &&
    149. Objects.equals(name, that.name) &&
    150. Objects.equals(gender, that.gender) &&
    151. Objects.equals(age, that.age) &&
    152. Objects.equals(msg, that.msg) &&
    153. Objects.equals(result, that.result);
    154. }
    155. @Override
    156. public int hashCode() {
    157. return Objects.hash(id, name, gender, age, msg, result);
    158. }
    159. }

    测试类:

    1. package com.example.java8.employees;
    2. import java.util.*;
    3. import java.util.stream.Collectors;
    4. /**
    5. *

    6. *
    7. * @author xpwi
    8. * @since 2022-08-14
    9. */
    10. public class TestJava8 {
    11. public static List oldList = new ArrayList<>();
    12. public static List newList = new ArrayList<>();
    13. static {
    14. initData();
    15. }
    16. /**
    17. * 初始化数据
    18. */
    19. public static void initData() {
    20. List result= new ArrayList<>();
    21. result.add("1d");
    22. result.add("25");
    23. result.add("3d");
    24. List result2= new ArrayList<>();
    25. result2.add("4d");
    26. result2.add("55");
    27. result2.add("6d");
    28. EmployeesVO employeesVO1 = null;
    29. employeesVO1 = new EmployeesVO.Bulider(1, "王二", 0, 25, "test1",result).bulider();
    30. oldList.add(employeesVO1);
    31. employeesVO1 = new EmployeesVO.Bulider(1, "王二", 0, 25, "test1",result).bulider();
    32. oldList.add(employeesVO1);
    33. employeesVO1= new EmployeesVO.Bulider(1, "王二", 1, 25, "test1",result).bulider();
    34. oldList.add(employeesVO1);
    35. employeesVO1 = new EmployeesVO.Bulider(4, "李慧", 1, 20, "test 4",result2).bulider();
    36. oldList.add(employeesVO1);
    37. employeesVO1 = new EmployeesVO.Bulider(5, "王二三", 0, 25, "test 5",result2).bulider();
    38. oldList.add(employeesVO1);
    39. List result4= new ArrayList<>();
    40. result2.add("1f");
    41. result2.add("e5");
    42. result2.add("1h");
    43. EmployeesVO employeesVO6 = new EmployeesVO.Bulider(6, "王二", 0, 25, "test 6",result2).bulider();
    44. EmployeesVO employeesVO7 = new EmployeesVO.Bulider(7, "李二", 0, 25, "test 7",result4).bulider();
    45. EmployeesVO employeesVO8 = new EmployeesVO.Bulider(8, "杨慧", 1, 23, "test 8",result4).bulider();
    46. EmployeesVO employeesVO9 = new EmployeesVO.Bulider(9, "周慧", 1, 20, "test 8",result4).bulider();
    47. EmployeesVO employeesVO10 = new EmployeesVO.Bulider(10, "周二", 0, 25, "test 10",result4).bulider();
    48. newList.add(employeesVO6);
    49. newList.add(employeesVO7);
    50. newList.add(employeesVO8);
    51. newList.add(employeesVO9);
    52. newList.add(employeesVO10);
    53. }
    54. /**
    55. * java常用函数:
    56. * 1,filter 代码的if操作,过滤数据
    57. * 2,map
    58. * 3,flatMap
    59. * 4,collect
    60. * 5,peek 调试 ,idea工具
    61. * 6,noneMatch,anyMatch
    62. * 7,skip
    63. * 8,distinct
    64. * 9,收集器 分组,sql group by
    65. * 分组,过滤,求和,平均,多个流合并,集合并集,交集,差集,map,集合转换
    66. *
    67. * @param args
    68. */
    69. public static void main(String args[]) {
    70. //filter 操作
    71. List result1 = oldList.stream().filter(employeesVO -> employeesVO.getName().equals("王二三")).collect(Collectors.toList());
    72. //集合差集 根据前面的对象来的
    73. List result2 = oldList.stream().filter(item-> !newList.stream().map(
    74. employees -> employees.getName()
    75. ).collect(Collectors.toList()).contains(item.getName())).collect(Collectors.toList());
    76. //俩个对象相同的交集
    77. List result3 = oldList.stream().filter(item->newList.stream().anyMatch(
    78. employeesVO -> Objects.equals(item.getName(),employeesVO.getName()))
    79. ).peek(employeesVO -> employeesVO.getGender()).collect(Collectors.toList());
    80. //去重
    81. List result4 = newList.stream().collect(
    82. Collectors.collectingAndThen(Collectors.toCollection(
    83. ()->new TreeSet<>(Comparator.comparing(o->o.getName()+":"+o.getId()))
    84. ),ArrayList::new));
    85. //分页
    86. // newList.stream().skip((i-1)*size).limit(size).collect(Collectors.toList());
    87. //flatmap 合并流
    88. List result5 = oldList.stream().map(m->m.getResult()).flatMap(Collection::stream).collect(Collectors.toList());
    89. //gropuby 分组
    90. Map > result6 = newList.stream().map(item->item).collect(Collectors.groupingBy(employeesVO -> employeesVO.getGender()));
    91. //收集器
    92. Map > result7 = newList.stream().collect(Collectors.partitioningBy(employeesVO -> employeesVO.getGender()==0));
    93. //distinct 去重 重写equeas 和hash方法
    94. List result8 = oldList.stream().distinct().collect(Collectors.toList());
    95. //map集合
    96. EmployeesVO employeesVO = new EmployeesVO.Bulider(6, "缓存", 0, 25, "缓存",null).bulider();
    97. cache.put("缓存",employeesVO);
    98. TestJava8 testJava8 = new TestJava8();
    99. EmployeesVO employeesVO1 =testJava8.getEmpCache("缓存222");
    100. EmployeesVO employeesVO3 =testJava8.getEmpCache("缓存222");
    101. System.out.println(result2);
    102. }
    103. public static Map cache = new HashMap<>();
    104. public EmployeesVO employeesVO(String name){
    105. EmployeesVO employeesVO = new EmployeesVO.Bulider(6, "缓存", 0, 25, "缓存",null).bulider();
    106. return employeesVO;
    107. }
    108. public EmployeesVO getEmpCache(String name){
    109. return cache.computeIfAbsent(name,this::employeesVO);
    110. }
    111. }

    filter 操作

    相对循环里面的if

    List beginningWithNumbers = new ArrayList<>();

    for(String value : asList("a", "1abc", "abc1")) {

    if (isDigit(value.charAt(0))) {

    beginningWithNumbers.add(value);

    }

    }

    assertEquals(asList("1abc"), beginningWithNumbers);

    flatMap 操作(多个流合并成一个流)

    一个对象的集合合并为一个对象

    List result = newList.stream().map(m->m.getResult()).flatMap(Collection::stream).collect(Collectors.toList());

    java8分页

    list.stream().skip((i - 1) * sheetSize).limit(sheetSize). collect(Collectors.toList());

    List newList2 = newList.stream().skip(( 1-1)* 2).limit(2).collect(Collectors.toList());
    List newList3 = newList.stream().skip(( 2 -1)*2).limit(2).collect(Collectors.toList());
    List newList4= newList.stream().skip(( 3 -1)*2).limit(2).collect(Collectors.toList());

    java8 集合取差集

    List result3 = newList.stream().filter(item-> !oldList.stream().map(
    employees -> employees.getName()
    ).collect(Collectors.toList()).contains(item.getName())).collect(Collectors.toList());

    java8根据参数过滤

    result2.stream().filter(m->m.getVehicleNo().equals(parms.get(0))).collect(Collectors.toList());

    java8集合对象多个值去重:

    newList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
    ()-> new TreeSet<>(Comparator.comparing(o -> o.getName()+":"+o.getId()))
    ), ArrayIter::new));

    java8取俩个对象相同的属性的值:

    List result= oldList.stream().filter(item->newList.stream().anyMatch(employees -> Objects.equals(employees.name, item.name))).collect(Collectors.toList());

    java8取前面个一个对象不相同的属性的值:


    List result= oldList.stream().filter(item->newList.stream().noneMatch(employees -> Objects.equals(employees.name, item.name))).collect(Collectors.toList());

    收集器:partitioningBy


    Map> map = newList.stream().collect(Collectors.partitioningBy(employDO -> 0==employDO.getGender()));

    groupingBy 收集器
    SQL 中的 group by 操作

    Map > resultFlter = newList.stream().map(m->m).collect(Collectors.groupingBy(employees -> employees.getName()));

    map集合函数:computeIfAbsent

    static Map artistCache = new HashMap<>();

    public Employees getAuthCenterVo(String unionId){
    Employees newEmployees = new Employees();
    newEmployees.setId(1222);
    newEmployees.setName("22222");
    newEmployees.setAge(2222);
    newEmployees.setGender(2222);
    return newEmployees;
    }
    public Employees getlist(String name) {
    return artistCache.computeIfAbsent(name, this::getAuthCenterVo);
    }

    调试解决方案:peak

    记录日志这是 peek 方法的用途之一。为了像调试循环那样一步一步跟踪,可在 peek 方法 中加入断点,这样就能逐个调试流中的元素了。 此时,peek 方法可知包含一个空的方法体,只要能设置断点就行。有一些调试器不允许在 空的方法体中设置断点,此时,我将值简单地映射为其本身,这样就有地方设置断点了, 虽然这样做不够完美,但只要能工作就行

    断点到方法调试

    peek方法

    示列1:

    List result = newList.stream().peek(
    m->System.out.println(m)
    ).collect(
    Collectors.collectingAndThen(
    Collectors.toCollection(() -> new TreeSet<>(
    Comparator.comparing(
    o->o.getName()+":"+o.getGender()))
    ),ArrayList::new ));

    示列2:
    long wordsList = Arrays.stream(test22.split(",")).map(m->m ).peek( t->System.out.println(t)).filter(textContent::equals)
    .count();

    idea调试

    常用的java8函数表达式就基本差不多这么多了,如果你需要了解其他的高阶的函数,可以去用@FuctionInterface注解操作

  • 相关阅读:
    React组件生命周期
    进程调度算法-时间片轮转、最高优先级和多级反馈队列调度算法
    深度之眼(十六)——Python:有益的探索
    【算法笔记】树状数组/Binary Indexed Tree/Fenwick Tree
    java毕业生设计医药网络挂号系统计算机源码+系统+mysql+调试部署+lw
    JAVAEE---多线程
    胆囊结石的危害你了解多少?
    深入分析LinkedHashMap
    【Mysql】where 条件子句之逻辑运算符
    【老卫搞机】090期:键盘?主机?全功能键盘主机!
  • 原文地址:https://blog.csdn.net/qq_39751120/article/details/126323823