将 2 个不同对象的列表合并为一个组合对象
Posted
技术标签:
【中文标题】将 2 个不同对象的列表合并为一个组合对象【英文标题】:Merge a list of 2 different objects into one combined object 【发布时间】: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());
【问题讨论】:
【参考方案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)
【讨论】:
以上是关于将 2 个不同对象的列表合并为一个组合对象的主要内容,如果未能解决你的问题,请参考以下文章