• Lambda 表达式练习


    目录

    sorted() 四种排序

    List 转 Map

    map 映射

    对象中 String 类型属性为空的字段赋值为 null

    BiConsumer,>

    T reduce(T identity, BinaryOperator accumulator)

    allMatch(Predicate p)

    groupingBy(Function f)

    flatMap(Function f)

    Optional.ofNullable(T t) 和 T orElse(T other)


    先来写个基本类

    1. public class LambdaTest {
    2. @Data
    3. class Student {
    4. private Integer id;
    5. private String name;
    6. private Integer age;
    7. public Student(Integer id, String name, Integer age) {
    8. this.id = id;
    9. this.name = name;
    10. this.age = age;
    11. }
    12. }
    13. public List getStudents() {
    14. List list = new ArrayList<>();
    15. list.add(new Student(100, "小明", 10));
    16. list.add(new Student(101, "小红", 11));
    17. list.add(new Student(102, "小李", 12));
    18. list.add(new Student(103, "小王", 13));
    19. list.add(new Student(104, "小张", 14));
    20. list.add(new Student(105, "小五", 15));
    21. list.add(new Student(106, "小华", 16));
    22. return list;
    23. }
    24. }

    sorted() 四种排序

    1. @Test
    2. public void sortedTest() {
    3. List students = this.getStudents();
    4. //正序:常规写法
    5. List collect = students.stream().sorted((a1, a2) -> Integer.compare(a1.getAge(), a2.getAge())).collect(Collectors.toList());
    6. collect.forEach(System.out::println);
    7. System.out.println();
    8. //正序:lambda 简写
    9. List collectComparator = students.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
    10. collectComparator.forEach(System.out::println);
    11. System.out.println();
    12. //倒序:常规写法
    13. List collectReversed = students.stream().sorted((a1, a2) -> Integer.compare(a2.getAge(), a1.getAge())).collect(Collectors.toList());
    14. collectReversed.forEach(System.out::println);
    15. System.out.println();
    16. //正序:lambda 简写
    17. List collectComparatorReversed = students.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());
    18. collectComparatorReversed.forEach(System.out::println);
    19. }

    List 转 Map

    1. @Test
    2. public void listToMapTest() {
    3. List students = this.getStudents();
    4. Map collect = students.stream().collect(Collectors.toMap(Student::getId, s -> s, (s1, s2) -> s1));
    5. collect.keySet().forEach(key -> System.out.println(String.format("key:%s,value:%s", key, collect.get(key))));
    6. }

    map 映射

    1. @Test
    2. public void mapTest() {
    3. List students = this.getStudents();
    4. // List students = Lists.newArrayList(new Student(null, "小炎姬", 5));
    5. Integer id = students.stream().map(Student::getId).max(Integer::compareTo).orElse(0);
    6. System.out.println(id);
    7. }

    对象中 String 类型属性为空的字段赋值为 null

    1. public static void stringEmptyToNull(T t) {
    2. Class clazz = t.getClass();
    3. Field[] fields = clazz.getDeclaredFields();
    4. Arrays.stream(fields)
    5. .filter(f -> f.getType() == String.class)
    6. .filter(f -> {
    7. try {
    8. f.setAccessible(true);
    9. String value = (String) f.get(t);
    10. return StringUtils.isEmpty(value);
    11. } catch (Exception ignore) {
    12. return false;
    13. }
    14. })
    15. .forEach(field -> {
    16. try {
    17. field.setAccessible(true);
    18. field.set(t, null);
    19. } catch (Exception ignore) {
    20. }
    21. });
    22. }

    BiConsumer

    1. <dependency>
    2. <groupId>org.projectlombokgroupId>
    3. <artifactId>lombokartifactId>
    4. <version>1.18.12version>
    5. dependency>
    6. <dependency>
    7. <groupId>com.google.guavagroupId>
    8. <artifactId>guavaartifactId>
    9. <version>28.2-jreversion>
    10. dependency>
    1. /**
    2. * @author vincent
    3. */
    4. public class LambdaTest {
    5. @Data
    6. private static class Student {
    7. private Integer id;
    8. private String name;
    9. private Integer age;
    10. private Integer interestType;
    11. private List hobbies;
    12. private List fancies;
    13. private Subject subject;
    14. private Student(Integer id, String name, Integer age, Integer interestType, List hobbies, List fancies, Subject subject) {
    15. this.id = id;
    16. this.name = name;
    17. this.age = age;
    18. this.interestType = interestType;
    19. this.hobbies = hobbies;
    20. this.fancies = fancies;
    21. this.subject = subject;
    22. }
    23. }
    24. enum InterestType {
    25. HOBBY(1, "兴趣"),
    26. FANCY(2, "喜好");
    27. private Integer code;
    28. private String message;
    29. InterestType(Integer code, String message) {
    30. this.code = code;
    31. this.message = message;
    32. }
    33. public Integer getCode() {
    34. return code;
    35. }
    36. public static InterestType getInterestTypeByCode(int code) {
    37. return Arrays.stream(InterestType.values()).filter(interestType -> interestType.getCode() == code).findFirst().orElse(null);
    38. }
    39. }
    40. @Data
    41. private static class Hobby {
    42. private String basketball;
    43. private String running;
    44. private String drinking;
    45. private Hobby(String basketball, String running, String drinking) {
    46. this.basketball = basketball;
    47. this.running = running;
    48. this.drinking = drinking;
    49. }
    50. }
    51. @Data
    52. private static class Fancy {
    53. private String dance;
    54. private String takePhotos;
    55. private String meetGirls;
    56. private Fancy(String dance, String takePhotos, String meetGirls) {
    57. this.dance = dance;
    58. this.takePhotos = takePhotos;
    59. this.meetGirls = meetGirls;
    60. }
    61. }
    62. @Data
    63. private static class Subject {
    64. private String english;
    65. private String chinese;
    66. private String mathematics;
    67. private Subject(String english, String chinese, String mathematics) {
    68. this.english = english;
    69. this.chinese = chinese;
    70. this.mathematics = mathematics;
    71. }
    72. }
    73. private List getStudent() {
    74. List list = Lists.newArrayList();
    75. list.add(new Student(100, "小明", 10, 1,
    76. Lists.newArrayList(
    77. new Hobby("篮球", "跑步", "喝酒"),
    78. new Hobby("篮球_1", "跑步_1", "喝酒_1"),
    79. new Hobby("篮球_2", "跑步_2", "喝酒_2"),
    80. new Hobby("篮球_3", "跑步_3", "喝酒_3")
    81. ),
    82. Lists.newArrayList(
    83. new Fancy("街舞", "摄影", "泡妞"),
    84. new Fancy("街舞_1", "摄影_1", "泡妞_1"),
    85. new Fancy("街舞_2", "摄影_2", "泡妞_2"),
    86. new Fancy("街舞_3", "摄影_3", "泡妞_3")
    87. ),
    88. new Subject("英语", "语文", "数学")
    89. ));
    90. list.add(new Student(200, "小红", 10, 2,
    91. Lists.newArrayList(
    92. new Hobby("篮球", "跑步", "喝酒"),
    93. new Hobby("篮球_1", "跑步_1", "喝酒_1"),
    94. new Hobby("篮球_2", "跑步_2", "喝酒_2"),
    95. new Hobby("篮球_3", "跑步_3", "喝酒_3")
    96. ),
    97. Lists.newArrayList(
    98. new Fancy("街舞", "摄影", "泡妞"),
    99. new Fancy("街舞_1", "摄影_1", "泡妞_1"),
    100. new Fancy("街舞_2", "摄影_2", "泡妞_2"),
    101. new Fancy("街舞_3", "摄影_3", "泡妞_3")
    102. ),
    103. new Subject("英语", "语文", "数学")
    104. ));
    105. return list;
    106. }
    107. @Data
    108. private static class Person {
    109. private Integer pid;
    110. private String pname;
    111. private Integer page;
    112. private String interest;
    113. private String subject;
    114. }
    115. private final static BiConsumer HOBBY = (person, student) -> {
    116. Optional.ofNullable(student.getHobbies())
    117. .flatMap(hobbies -> hobbies.stream().findFirst())
    118. .ifPresent(hobby -> person.setInterest(hobby.getDrinking()));
    119. Optional.ofNullable(student.subject).ifPresent(subject -> person.setSubject(subject.getEnglish()));
    120. };
    121. private final static BiConsumer FANCY = (person, student) -> {
    122. Optional.ofNullable(student.getFancies())
    123. .flatMap(fancies -> fancies.stream().findFirst())
    124. .ifPresent(fancy -> person.setInterest(fancy.getDance()));
    125. Optional.ofNullable(student.subject).ifPresent(subject -> person.setSubject(subject.getMathematics()));
    126. };
    127. private final static ImmutableMap> OF = ImmutableMap.of(
    128. InterestType.HOBBY, HOBBY,
    129. InterestType.FANCY, FANCY
    130. );
    131. /**
    132. * BiConsumer 实例
    133. */
    134. @Test
    135. public void t() {
    136. List studentList = getStudent();
    137. List collect = studentList.stream().map(student -> {
    138. Person person = new Person();
    139. Optional.ofNullable(student).ifPresent(stu -> {
    140. person.setPid(stu.getId());
    141. person.setPname(stu.getName());
    142. person.setPage(stu.getAge());
    143. Integer interestType = student.getInterestType();
    144. InterestType interestTypeByCode = InterestType.getInterestTypeByCode(interestType);
    145. person.setInterest(interestTypeByCode.message);
    146. OF.get(interestTypeByCode).accept(person, student);
    147. });
    148. return person;
    149. }).collect(Collectors.toList());
    150. System.out.println(collect);
    151. }
    152. }
    153. T reduce(T identity, BinaryOperator accumulator)

      1. org.apache.commons
      2. commons-lang3
      3. 3.9

      1. /**
      2. * @author qfxl
      3. */
      4. public class LambdaTest {
      5. @Data
      6. private static class trip {
      7. private String departure;
      8. private String destination;
      9. private trip(String departure, String destination) {
      10. this.departure = departure;
      11. this.destination = destination;
      12. }
      13. }
      14. /**
      15. * reduce 规则:
      16. * 例子:1.上海 -> 北京
      17. * 2.北京 -> 上海
      18. * 3.天津 -> 西安
      19. * 4.拉萨 -> 灵芝
      20. * 5.灵芝 -> 兰州
      21. * 6.兰州 -> 西宁
      22. * 展示效果:上海-北京-上海,天津-西安,拉萨-灵芝-兰州-西宁
      23. */
      24. private static final BinaryOperator ACCUMULATOR = (v1, v2) -> {
      25. if (StringUtils.isEmpty(v1)) {
      26. return v2;
      27. }
      28. String[] item = StringUtils.split(v1, ",");
      29. String[] lastOfItem = StringUtils.split(item[item.length - 1], "-");
      30. String lastElement = lastOfItem[lastOfItem.length - 1];
      31. String[] nextItem = StringUtils.split(v2, "-");
      32. String startElement = nextItem[0];
      33. if (StringUtils.equals(lastElement, startElement)) {
      34. return v1 + "-" + nextItem[nextItem.length - 1];
      35. }
      36. return v1 + "," + v2;
      37. };
      38. @Test
      39. public void t2() {
      40. List list = Lists.newArrayList(
      41. new trip("上海", "北京"),
      42. new trip("北京", "上海"),
      43. new trip("天津", "西安"),
      44. new trip("拉萨", "灵芝"),
      45. new trip("灵芝", "兰州"),
      46. new trip("兰州", "西宁")
      47. );
      48. //[上海-北京-上海,天津-西安,拉萨-灵芝-兰州-西宁]
      49. String reduce = list.stream()
      50. .map(t -> String.format("%s-%s", t.getDeparture(), t.getDestination()))
      51. .reduce("", ACCUMULATOR);
      52. System.out.println(reduce);
      53. }
      54. }

      allMatch(Predicate p)

      1. public static final String YYYYMMDD = "yyyyMMdd";
      2. public static final String YYYY_MM_DD = "yyyy-MM-dd";
      3. public static final String YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";
      4. public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
      5. public static final String YYYY__MM__DD = "yyyy/MM/dd";
      6. public static final String YYYY__MM__DD_HH_MM = "yyyy/MM/dd HH:mm";
      7. public static final String YYYY__MM__DD_HH_MM_SS = "yyyy/MM/dd HH:mm:ss";
      8. @Test
      9. public void t3() {
      10. @Data
      11. class DateValidate {
      12. private String date;
      13. private String dateFormat;
      14. public DateValidate(String date, String dateFormat) {
      15. this.date = date;
      16. this.dateFormat = dateFormat;
      17. }
      18. }
      19. List list = Lists.newArrayList(
      20. new DateValidate("202086", YYYYMMDD),
      21. new DateValidate("2020086", YYYYMMDD),
      22. new DateValidate("2020806", YYYYMMDD),
      23. new DateValidate("20200806", YYYYMMDD),
      24. new DateValidate("20200806 19", null),
      25. new DateValidate("20200806 19:00", null),
      26. new DateValidate("20200806 19:00:00", null),
      27. new DateValidate("2020-8-06", YYYY_MM_DD),
      28. new DateValidate("2020-08-6", YYYY_MM_DD),
      29. new DateValidate("2020-08-06", YYYY_MM_DD),
      30. new DateValidate("2020-08-06 19", null),
      31. new DateValidate("2020-08-06 19:00", YYYY_MM_DD_HH_MM),
      32. new DateValidate("2020-08-06 19:00:00", YYYY_MM_DD_HH_MM_SS),
      33. new DateValidate("2020/8/06", YYYY__MM__DD),
      34. new DateValidate("2020/08/6", YYYY__MM__DD),
      35. new DateValidate("2020/08/06", YYYY__MM__DD),
      36. new DateValidate("2020/08/06 19", null),
      37. new DateValidate("2020/08/06 19:00", YYYY__MM__DD_HH_MM),
      38. new DateValidate("2020/08/06 19:00:00", YYYY__MM__DD_HH_MM_SS)
      39. );
      40. list.forEach(item -> {
      41. boolean matchDateTime = matchDateTime(item.getDate());
      42. System.out.println(item.getDate() + " (" + item.getDateFormat() + "):matchDateTime -> " + matchDateTime);
      43. });
      44. }
      45. /**
      46. * 时间校验
      47. * @param dateTime
      48. * @return
      49. */
      50. public static boolean matchDateTime(String dateTime) {
      51. if (StringUtils.isEmpty(dateTime)) {
      52. return false;
      53. }
      54. String[] dt = dateTime.split("\\s+");
      55. if (dt.length == 1) {
      56. return dateMatch(dt[0], "/") || dateMatch(dt[0], "-");
      57. } else {
      58. String date = dt[0];
      59. String time = dt[1];
      60. return (dateMatch(date, "/") || dateMatch(date, "-")) && timeMatch(time, ":");
      61. }
      62. }
      63. private static boolean timeMatch(String s, String split) {
      64. if (StringUtils.isEmpty(s)) {
      65. return true;
      66. }
      67. s = StringUtils.trim(s);
      68. String[] time = StringUtils.split(s, split);
      69. boolean isNumber = Arrays.stream(time).anyMatch(StringUtils::isNumeric);
      70. if (!isNumber) {
      71. return false;
      72. }
      73. if (time.length != 3) {
      74. return false;
      75. }
      76. if (time[0].length() > 2 || Integer.parseInt(time[0]) > 24) {
      77. return false;
      78. }
      79. if (time[1].length() > 2 || Integer.parseInt(time[1]) > 60) {
      80. return false;
      81. }
      82. if (time[2].length() > 2 || Integer.parseInt(time[2]) > 60) {
      83. return false;
      84. }
      85. return true;
      86. }
      87. private static boolean dateMatch(String s, String spl) {
      88. if (StringUtils.isEmpty(s)) {
      89. return false;
      90. }
      91. s = StringUtils.trim(s);
      92. String[] date = StringUtils.split(s, spl);
      93. boolean isNumber = Arrays.stream(date).anyMatch(StringUtils::isNumeric);
      94. if (!isNumber) {
      95. return false;
      96. }
      97. if (date.length != 3) {
      98. return false;
      99. }
      100. if (date[0].length() != 4) {
      101. return false;
      102. }
      103. if (Integer.parseInt(date[1]) > 12) {
      104. return false;
      105. }
      106. if (Integer.parseInt(date[2]) > 31) {
      107. return false;
      108. }
      109. return true;
      110. }

      显示结果

      1. 202086 (yyyyMMdd):matchDateTime -> false
      2. 2020086 (yyyyMMdd):matchDateTime -> false
      3. 2020806 (yyyyMMdd):matchDateTime -> false
      4. 20200806 (yyyyMMdd):matchDateTime -> false
      5. 20200806 19 (null):matchDateTime -> false
      6. 20200806 19:00 (null):matchDateTime -> false
      7. 20200806 19:00:00 (null):matchDateTime -> false
      8. 2020-8-06 (yyyy-MM-dd):matchDateTime -> true
      9. 2020-08-6 (yyyy-MM-dd):matchDateTime -> true
      10. 2020-08-06 (yyyy-MM-dd):matchDateTime -> true
      11. 2020-08-06 19 (null):matchDateTime -> false
      12. 2020-08-06 19:00 (yyyy-MM-dd HH:mm):matchDateTime -> false
      13. 2020-08-06 19:00:00 (yyyy-MM-dd HH:mm:ss):matchDateTime -> true
      14. 2020/8/06 (yyyy/MM/dd):matchDateTime -> true
      15. 2020/08/6 (yyyy/MM/dd):matchDateTime -> true
      16. 2020/08/06 (yyyy/MM/dd):matchDateTime -> true
      17. 2020/08/06 19 (null):matchDateTime -> false
      18. 2020/08/06 19:00 (yyyy/MM/dd HH:mm):matchDateTime -> false
      19. 2020/08/06 19:00:00 (yyyy/MM/dd HH:mm:ss):matchDateTime -> true

      groupingBy(Function f)

      1. @Test
      2. public void t5() {
      3. @Data
      4. class Stu {
      5. private Integer id;
      6. private String name;
      7. private Long money;
      8. public Stu(Integer id, String name, Long money) {
      9. this.id = id;
      10. this.name = name;
      11. this.money = money;
      12. }
      13. }
      14. List list = Lists.newArrayList(
      15. new Stu(1, "小明", 100L),
      16. new Stu(1, "小红", 200L),
      17. new Stu(2, "小黄", 200L),
      18. new Stu(2, "小紫", 200L)
      19. );
      20. Map> collect = list.stream().collect(Collectors.groupingBy(Stu::getId));
      21. System.out.println(JSON.toJSONString(collect, SerializerFeature.PrettyFormat));
      22. }

      显示结果

      1. {1:[
      2. {
      3. "id":1,
      4. "money":100,
      5. "name":"小明"
      6. },
      7. {
      8. "id":1,
      9. "money":200,
      10. "name":"小红"
      11. }
      12. ],2:[
      13. {
      14. "id":2,
      15. "money":200,
      16. "name":"小黄"
      17. },
      18. {
      19. "id":2,
      20. "money":200,
      21. "name":"小紫"
      22. }
      23. ]
      24. }

      flatMap(Function f)

      1. @Data
      2. private static class TravelInfo {
      3. private String trip;
      4. private String hotelName;
      5. private List orders;
      6. public TravelInfo(String trip, String hotelName, List orders) {
      7. this.trip = trip;
      8. this.hotelName = hotelName;
      9. this.orders = orders;
      10. }
      11. }
      12. @Data
      13. private static class Order {
      14. private Long orderId;
      15. private List travellers;
      16. public Order(Long orderId, List travellers) {
      17. this.orderId = orderId;
      18. this.travellers = travellers;
      19. }
      20. }
      21. @Data
      22. private static class Travellers {
      23. private String userName;
      24. private String email;
      25. public Travellers() {
      26. }
      27. public Travellers(String userName, String email) {
      28. this.userName = userName;
      29. this.email = email;
      30. }
      31. }
      32. /**
      33. * flatMap(Function f):扁平化
      34. */
      35. @Test
      36. public void t5() {
      37. TravelInfo travelInfo = new TravelInfo("三人行", "天上人间",
      38. Lists.newArrayList(
      39. new Order(123456789L, Lists.newArrayList(
      40. new Travellers("zhangSanFirst", "zhangSanFirst@qq.com"),
      41. new Travellers("zhangSanSecond", "zhangSanSecond@qq.com")
      42. )),
      43. new Order(987654321L, Lists.newArrayList(
      44. new Travellers("liSiFirst", "zhangSanFirst@qq.com"),
      45. new Travellers("liSiSecond", "zhangSanSecond@qq.com")
      46. )),
      47. new Order(987654322L, Lists.newArrayList(
      48. new Travellers("wangWu", "wangWu@qq.com")
      49. )),
      50. new Order(987654323L, Lists.newArrayList()),
      51. new Order(987654323L, null)
      52. ));
      53. System.out.println(JSON.toJSONString(travelInfo, SerializerFeature.PrettyFormat));
      54. System.out.println();
      55. List email = travelInfo.getOrders().stream()
      56. .filter(Objects::nonNull)
      57. .map(Order::getTravellers)
      58. .filter(CollectionUtils::isNotEmpty)
      59. .flatMap(Collection::stream)
      60. .filter(Objects::nonNull)
      61. .map(Travellers::getEmail)
      62. .collect(Collectors.toList());
      63. System.out.println(email);
      64. }

      显示结果

      1. {
      2. "hotelName":"天上人间",
      3. "orders":[
      4. {
      5. "orderId":123456789,
      6. "travellers":[
      7. {
      8. "email":"zhangSanFirst@qq.com",
      9. "userName":"zhangSanFirst"
      10. },
      11. {
      12. "email":"zhangSanSecond@qq.com",
      13. "userName":"zhangSanSecond"
      14. }
      15. ]
      16. },
      17. {
      18. "orderId":987654321,
      19. "travellers":[
      20. {
      21. "email":"zhangSanFirst@qq.com",
      22. "userName":"liSiFirst"
      23. },
      24. {
      25. "email":"zhangSanSecond@qq.com",
      26. "userName":"liSiSecond"
      27. }
      28. ]
      29. },
      30. {
      31. "orderId":987654322,
      32. "travellers":[
      33. {
      34. "email":"wangWu@qq.com",
      35. "userName":"wangWu"
      36. }
      37. ]
      38. },
      39. {
      40. "orderId":987654323,
      41. "travellers":[]
      42. },
      43. {
      44. "orderId":987654323
      45. }
      46. ],
      47. "trip":"三人行"
      48. }
      49. [zhangSanFirst@qq.com, zhangSanSecond@qq.com, zhangSanFirst@qq.com, zhangSanSecond@qq.com, wangWu@qq.com]

      Optional.ofNullable(T t) 和 T orElse(T other)

      1. @Data
      2. private class PaymentDto {
      3. private Long id;
      4. private String liqAccountName;
      5. /**
      6. * 来款业务:COMPANY-企业来款;OFFLINE-订单线下收款
      7. */
      8. private String paymentMode;
      9. private List claimDto;
      10. private List orderClaimDto;
      11. public PaymentDto(Long id, String liqAccountName, String paymentMode, List claimDto, List orderClaimDto) {
      12. this.id = id;
      13. this.liqAccountName = liqAccountName;
      14. this.paymentMode = paymentMode;
      15. this.claimDto = claimDto;
      16. this.orderClaimDto = orderClaimDto;
      17. }
      18. }
      19. @Data
      20. private static class ClaimDto {
      21. private Long paymentId;
      22. private String partnerName;
      23. private Integer amount;
      24. public ClaimDto(Long paymentId, String partnerName, Integer amount) {
      25. this.paymentId = paymentId;
      26. this.partnerName = partnerName;
      27. this.amount = amount;
      28. }
      29. }
      30. @Data
      31. private static class OrderClaimDto {
      32. private Long paymentId;
      33. private Integer amount;
      34. public OrderClaimDto(Long paymentId, Integer amount) {
      35. this.paymentId = paymentId;
      36. this.amount = amount;
      37. }
      38. }
      39. @Data
      40. private static class PaymentApiDto {
      41. private Long id;
      42. private String liqAccountName;
      43. private String paymentMode;
      44. private Long paymentId;
      45. private String partnerName;
      46. private Integer amount;
      47. }
      48. private List getPaymentDto() {
      49. List list = Lists.newArrayList();
      50. list.add(new PaymentDto(123456789L, "收款账户_COMPANY", "COMPANY",
      51. Lists.newArrayList(
      52. new ClaimDto(123456789L, "企业名称1", 999),
      53. new ClaimDto(123456789L, "企业名称2", 888),
      54. new ClaimDto(123456789L, "企业名称3", 777)
      55. ),
      56. Lists.newArrayList(
      57. new OrderClaimDto(123456789L, 666),
      58. new OrderClaimDto(123456789L, 555)
      59. )));
      60. list.add(new PaymentDto(987654321L, "收款账户_OFFLINE", "OFFLINE",
      61. Lists.newArrayList(
      62. new ClaimDto(987654321L, "企业名称1", 999),
      63. new ClaimDto(987654321L, "企业名称2", 888)
      64. ),
      65. Lists.newArrayList(
      66. new OrderClaimDto(987654321L, 666),
      67. new OrderClaimDto(987654321L, 555)
      68. )));
      69. list.add(new PaymentDto(888888888L, "收款账户", null, null, null));
      70. return list;
      71. }
      72. /**
      73. * Optional.ofNullable(T t) 和 T orElse(T other)
      74. */
      75. @Test
      76. public void t6() {
      77. List paymentDtos = getPaymentDto();
      78. paymentDtos.forEach(System.out::println);
      79. System.out.println();
      80. /**
      81. * 根据 paymentMode 把 claimDto、orderClaimDto 集合数据查分为单条数据
      82. */
      83. List collect = paymentDtos
      84. .stream()
      85. .map(paymentDto -> {
      86. PaymentApiDto apiDto = new PaymentApiDto();
      87. apiDto.setId(paymentDto.getId());
      88. apiDto.setLiqAccountName(paymentDto.getLiqAccountName());
      89. apiDto.setPaymentMode(paymentDto.getPaymentMode());
      90. ImmutableList defaultList = ImmutableList.of(apiDto);
      91. if (StringUtils.equals(paymentDto.getPaymentMode(), "COMPANY")) {
      92. return Optional.ofNullable(paymentDto.getClaimDto())
      93. .map(claimDtos -> claimDtos.stream()
      94. .map(claimDto -> {
      95. PaymentApiDto paymentApiDto = new PaymentApiDto();
      96. paymentApiDto.setId(paymentDto.getId());
      97. paymentApiDto.setLiqAccountName(paymentDto.getLiqAccountName());
      98. paymentApiDto.setPaymentMode(paymentDto.getPaymentMode());
      99. paymentApiDto.setPaymentId(claimDto.getPaymentId());
      100. paymentApiDto.setPartnerName(claimDto.getPartnerName());
      101. paymentApiDto.setAmount(claimDto.getAmount());
      102. return paymentApiDto;
      103. })
      104. .collect(Collectors.toList())
      105. )
      106. .orElse(defaultList);
      107. }
      108. if (StringUtils.equals(paymentDto.getPaymentMode(), "OFFLINE")) {
      109. return Optional.ofNullable(paymentDto.getOrderClaimDto())
      110. .map(orderClaimDtos -> orderClaimDtos.stream()
      111. .map(orderClaimDto -> {
      112. PaymentApiDto paymentApiDto = new PaymentApiDto();
      113. paymentApiDto.setId(paymentDto.getId());
      114. paymentApiDto.setLiqAccountName(paymentDto.getLiqAccountName());
      115. paymentApiDto.setPaymentMode(paymentDto.getPaymentMode());
      116. paymentApiDto.setAmount(orderClaimDto.getAmount());
      117. return paymentApiDto;
      118. })
      119. .collect(Collectors.toList())
      120. )
      121. .orElse(defaultList);
      122. }
      123. return defaultList;
      124. })
      125. .flatMap(Collection::stream)
      126. .collect(Collectors.toList());
      127. collect.forEach(System.out::println);
      128. }

      显示结果

      1. LambdaTest.PaymentDto(id=123456789, liqAccountName=收款账户_COMPANY, paymentMode=COMPANY, claimDto=[LambdaTest.ClaimDto(paymentId=123456789, partnerName=企业名称1, amount=999), LambdaTest.ClaimDto(paymentId=123456789, partnerName=企业名称2, amount=888), LambdaTest.ClaimDto(paymentId=123456789, partnerName=企业名称3, amount=777)], orderClaimDto=[LambdaTest.OrderClaimDto(paymentId=123456789, amount=666), LambdaTest.OrderClaimDto(paymentId=123456789, amount=555)])
      2. LambdaTest.PaymentDto(id=987654321, liqAccountName=收款账户_OFFLINE, paymentMode=OFFLINE, claimDto=[LambdaTest.ClaimDto(paymentId=987654321, partnerName=企业名称1, amount=999), LambdaTest.ClaimDto(paymentId=987654321, partnerName=企业名称2, amount=888)], orderClaimDto=[LambdaTest.OrderClaimDto(paymentId=987654321, amount=666), LambdaTest.OrderClaimDto(paymentId=987654321, amount=555)])
      3. LambdaTest.PaymentDto(id=888888888, liqAccountName=收款账户, paymentMode=null, claimDto=null, orderClaimDto=null)
      4. LambdaTest.PaymentApiDto(id=123456789, liqAccountName=收款账户_COMPANY, paymentMode=COMPANY, paymentId=123456789, partnerName=企业名称1, amount=999)
      5. LambdaTest.PaymentApiDto(id=123456789, liqAccountName=收款账户_COMPANY, paymentMode=COMPANY, paymentId=123456789, partnerName=企业名称2, amount=888)
      6. LambdaTest.PaymentApiDto(id=123456789, liqAccountName=收款账户_COMPANY, paymentMode=COMPANY, paymentId=123456789, partnerName=企业名称3, amount=777)
      7. LambdaTest.PaymentApiDto(id=987654321, liqAccountName=收款账户_OFFLINE, paymentMode=OFFLINE, paymentId=null, partnerName=null, amount=666)
      8. LambdaTest.PaymentApiDto(id=987654321, liqAccountName=收款账户_OFFLINE, paymentMode=OFFLINE, paymentId=null, partnerName=null, amount=555)
      9. LambdaTest.PaymentApiDto(id=888888888, liqAccountName=收款账户, paymentMode=null, paymentId=null, partnerName=null, amount=null)
    154. 相关阅读:
      C++之operator()和构造函数区别与总结(二百三十)
      Nacos 服务治理(服务注册中心)
      mulesoft Module 13 quiz 解析
      Linux wait函数用法
      Spring:怨种的我和这玩意死磕到半夜12点20的这件事?
      我做测试开发的这一年多,月薪5K变成了24K
      牵手时代少年团,来伊份讲了一个“新鲜”故事
      判断当前时间是否在指定时间区间(时间段)内
      QT基础 柱状图
      Linux 基础-查看和设置环境变量
    155. 原文地址:https://blog.csdn.net/qq_24907431/article/details/139399247