【问题标题】:Merge a list of 2 different objects into one combined object将 2 个不同对象的列表合并为一个组合对象
【发布时间】:2021-10-29 06:28:17
【问题描述】:

我需要将两个列表List<Phone>List<PhoneTwo>合并为一个组合对象Combined,在Combined中只有一个字段,即phone

[
    {
        "phones": [
            {
                "id": 1,
                "phone": "44444444"
            },
            {
                "id": 2,
                "phone": "5555555"
            }
        ],
        "phonesTwo": [
            {
                "id": 1,
                "phone": "77777777"
            },
            {
                "id": 2,
                "phone": "66666666"
            }
        ],
        "combined": null
    }
]

预期结果是:

[
    {
        "phones": [
                    //data removed for brevity
        ],
        "phonesTwo": [
                    //data removed for brevity 
        ],
        "combined": [
            {
                "phone": "44444444"
            },
            {
                "phone": "5555555"
            },
            {
                "phone": "77777777"
            },
            {
                "phone": "77777777"
            }
        ]
    }
]

尝试使用flatmap,但卡在了这里,我应该如何继续?

employee.getPhones()
               .stream()
               .flatMap(employee.getPhonesTwo().stream()
                        .map(two -> {
                             Combined combined = new  Combined();
                              //not sure what to do here
                        })).collect(Collectors.toList());

【问题讨论】:

    标签: java-8 java-stream flatmap


    【解决方案1】:
    class Combined {
      String phone;
    
      public Combined(String phone) {
        this.phone = phone;
      }
    }
    

    只需迭代两个列表并将新对象与手机添加到组合数组中

    ArrayList<Combined> combined = new ArrayList<Combined>()    
    
    for(obj in employee.getPhones()) {
      combined.add(new Combined(obj.phone))
    }
    
    for(obj in employee.getPhonesTwo()) {
      combined.add(new Combined(obj.phone))
    }
    
    System.out.println(combined)
    

    【讨论】:

      猜你喜欢
      • 2018-04-21
      • 2019-09-08
      • 2019-10-07
      • 1970-01-01
      • 2017-09-22
      • 2018-02-09
      • 2021-09-10
      • 2020-11-28
      • 2015-02-16
      相关资源
      最近更新 更多