当前位置:   article > 正文

用Stream流方式合并两个list集合(部分对象属性重合)

用Stream流方式合并两个list集合(部分对象属性重合)

一、合并出共有部分

  1. package com.xu.demo.test;
  2. import java.util.Arrays;
  3. import java.util.List;
  4. import java.util.stream.Collectors;
  5. public class ListMergeTest1 {
  6. public static void main(String[] args) {
  7. List<User> list1 = Arrays.asList(new User(1, "Alice"), new User(2, "Bob"), new User(4, "Ronnie"));
  8. List<User> list2 = Arrays.asList(new User(2, "Bobby"), new User(3, "Charlie"), new User(5, "Trump"));
  9. List<User> mergedList = list1.stream()
  10. .flatMap(user1 -> list2.stream()
  11. .filter(user2 -> user1.getId() == user2.getId())
  12. .map(user2 -> {
  13. User newUser = new User();
  14. newUser.setId(user2.getId());
  15. newUser.setName(user2.getName());
  16. return newUser;
  17. })
  18. )
  19. .collect(Collectors.toList());
  20. mergedList.forEach(System.out::println);
  21. }
  22. }
  23. class User {
  24. private int id;
  25. private String name;
  26. public User(int id, String name) {
  27. this.id = id;
  28. this.name = name;
  29. }
  30. // Getter and Setter methods
  31. public int getId() {
  32. return id;
  33. }
  34. public String getName() {
  35. return name;
  36. }
  37. public void setId(int id) {
  38. this.id = id;
  39. }
  40. public void setName(String name) {
  41. this.name = name;
  42. }
  43. public User() {
  44. }
  45. @Override
  46. public String toString() {
  47. return "User{" +
  48. "id=" + id +
  49. ", name='" + name + '\'' +
  50. '}';
  51. }
  52. }

运行结果:注意流处理中return的位置

二、合并到某一List(假如保留到第一个List)

  1. package com.xu.demo.test;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. import java.util.stream.Collectors;
  7. public class ListMergeTest2 {
  8. public static void main(String[] args) {
  9. List<Map<String,Object>> list1 = new ArrayList<>();
  10. Map<String,Object> data=new HashMap<>();
  11. data.put("userId","100001");
  12. data.put("userName","唐僧");
  13. list1.add(data);
  14. data=new HashMap<>();
  15. data.put("userId","100002");
  16. data.put("userName","八戒");
  17. list1.add(data);
  18. List<Map<String,Object>> list2 = new ArrayList<>();
  19. data=new HashMap<>();
  20. data.put("userId","100001");
  21. data.put("gender","男");
  22. data.put("age",20);
  23. list2.add(data);
  24. data=new HashMap<>();
  25. data.put("userId","100002");
  26. data.put("gender","雄");
  27. data.put("age",1000);
  28. list2.add(data);
  29. System.out.println(list1);
  30. System.out.println(list2);
  31. //使用stream流把list1和list2根据属性userId合并一个list集合
  32. list1.stream().map(m1 -> {
  33. list2.stream().filter(m2 -> m1.get("userId").equals(m2.get("userId"))).forEach( m2 -> {
  34. m1.put("gender", m2.get("gender"));
  35. m1.put("age", m2.get("age"));
  36. });
  37. return m1;
  38. }).collect(Collectors.toList());
  39. System.out.println(list1);
  40. System.out.println(list2);
  41. }
  42. }

运行结果如下:注意流处理中return的位置

三、合并成新对象列表

  1. package com.xu.demo.test;
  2. import com.alibaba.fastjson.JSON;
  3. import lombok.Data;
  4. import org.apache.commons.lang3.StringUtils;
  5. import java.util.Arrays;
  6. import java.util.List;
  7. import java.util.stream.Collectors;
  8. public class Test {
  9. public static void main(String[] args) {
  10. new Test().test();
  11. }
  12. public void test(){
  13. List<Person> userListA = Arrays.asList(
  14. new Person("关羽", 926),
  15. new Person("赵云", 916),
  16. new Person("张飞", 906),
  17. new Person("许褚", 911));
  18. List<Rule> userListB = Arrays.asList(
  19. new Rule("关羽", "字·云长-关公-武财神-汉寿亭侯"),
  20. new Rule("张飞", "字·益德-勇武过人-西乡侯"),
  21. new Rule("刘备", "字·玄德-百折不挠-汉昭烈帝"),
  22. new Rule("赵云", "字·子龙-忠义-永昌亭侯"),
  23. new Rule("周瑜", "字·公瑾-文武兼备-永昌亭侯"),
  24. new Rule("许褚", "字·仲康-勇力绝人-虎侯"));
  25. List<Hero> commonList = userListA.stream()
  26. .map(uA -> userListB.stream()
  27. .filter(uB1 -> StringUtils.equals(uB1.getUserName(), uA.getUserName()))
  28. .map(uB2 -> new Hero(uB2.getUserName(), uA.getBloodVolume(), uB2.getAlign()))
  29. .collect(Collectors.toList())) // 结果类型 Steam<List<Hero>>
  30. .flatMap(List::stream) // 结果类型 Steam<Hero>
  31. .collect(Collectors.toList()); // 结果类型 List<Hero>
  32. System.out.println(JSON.toJSONString(commonList));
  33. // [{"align":"字·云长-关公-武财神-汉寿亭侯","bloodVolume":926,"userName":"关羽"},
  34. // {"align":"字·子龙-忠义-永昌亭侯","bloodVolume":916,"userName":"赵云"},
  35. // {"align":"字·益德-勇武过人-西乡侯","bloodVolume":906,"userName":"张飞"},
  36. // {"align":"字·仲康-勇力绝人-虎侯","bloodVolume":911,"userName":"许褚"}]
  37. }
  38. }
  39. @Data
  40. class Person {
  41. private String userName;
  42. private int bloodVolume;
  43. public Person(String userName, int bloodVolume) {
  44. this.userName = userName;
  45. this.bloodVolume = bloodVolume;
  46. }
  47. }
  48. @Data
  49. class Rule {
  50. private String userName;
  51. private String align;
  52. public Rule(String userName, String align) {
  53. this.userName = userName;
  54. this.align = align;
  55. }
  56. }
  57. @Data
  58. class Hero {
  59. private String userName;
  60. private int bloodVolume;
  61. private String align;
  62. public Hero(String userName, int bloodVolume, String align) {
  63. this.userName = userName;
  64. this.bloodVolume = bloodVolume;
  65. this.align = align;
  66. }
  67. }

Java8的流式处理提供了大量强大而且简单的数据(结构)处理,一定要好好总结学习,对你的编程思维和能能力的提高大有好处。 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/535602
推荐阅读
相关标签
  

闽ICP备14008679号