如:角色去重处理
baseRoleList = baseRoleList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(role -> role.getRoleId()))), ArrayList::new));

原文链接:
https://blog.csdn.net/qq_28988969/article/details/81119587

原文内容:

背景

有一个list,实体包含多个字段,当其中两个字段值均相同时,就认为list中的这两条记录是一样的

去重

java8中有一个collectingAndThen可以根据多个字段去重
依据姓名和年龄去重,当姓名和年龄相同时,认为这两个实体相同

  1. class FlightTicketInfo {
  2. private String orderNumber;
  3. private String userName;
  4. private String age;
  5. public FlightTicketInfo(String orderNumber, String userName, String age) {
  6. this.orderNumber = orderNumber;
  7. this.userName = userName;
  8. this.age = age;
  9. }
  10. @Override
  11. public String toString() {
  12. return "FlightTicketInfo{" +
  13. "orderNumber='" + orderNumber + '\'' +
  14. ", userName='" + userName + '\'' +
  15. ", age='" + age + '\'' +
  16. '}';
  17. }
  18. public String getOrderNumber() {
  19. return orderNumber;
  20. }
  21. public String getUserName() {
  22. return userName;
  23. }
  24. public String getAge() {
  25. return age;
  26. }
  27. }
  28. @Test
  29. public void testList(){
  30. List<FlightTicketInfo> infoList = new ArrayList<>();
  31. infoList.add(new FlightTicketInfo("11111", "xiaoming", "22"));
  32. infoList.add(new FlightTicketInfo("22222", "xiaoming", "22"));
  33. infoList.add(new FlightTicketInfo("33333", "xiaoming", "23"));
  34. infoList.add(new FlightTicketInfo("11111", "xiaoming", "22"));
  35. infoList.stream()
  36. .collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(f -> f.getUserName()+f.getAge()))), ArrayList::new))
  37. .forEach(System.out::println);
  38. }