英文:
iterating over two java streams with the same size and override values from one on another
问题
我有两个列表,它们的大小相同。我想同时迭代这两个列表,并将一个列表中的值覆盖到另一个列表中。
例如,我有两个列表 ListA 和 ListB,其中包含一些数据,它们可以通过 id 进行比较,我想要得到如下结果:
List<SomeObject> listA;
List<AnotherObject> listB;
listA: [
[id=111;
name='AAA';
age=65],
[id=222;
name='BBB';
age=11]
]
listB: [
[id=111;
name='';
age=null],
[id=222;
name='';
age=null]
]
result: [
[id=111;
name='AAA';
age=65],
[id=222;
name='BBB';
age=11]
]
它们当然还有一些其他不同的属性,应该保持原样。所以我只需要覆盖其中的两个属性。
英文:
I have two Lists and they have same size. I would like to iterate over both of them simultaneously and override values from one stream on another stream.
For example I have two lists ListA and ListB with some data and they can be compared by id and I would like to get as a result like below:
List<SomeObject> listA;
List<AnotherObject> listB;
listA: {
[id=111;
name='AAA';
age=65],
[id=222;
name='BBB';
age=11],
}
listB: {
[id=111;
name='';
age=null],
[id=222;
name='';
age=null],
}
result:{
[id=111;
name='AAA';
age=65],
[id=222;
name='BBB';
age=11],
}
They have some other properties of course which are different and should stay as it is. So I need to override just two of them
答案1
得分: 1
Sure, here's the translation:
- 从一个列表(按
id
分组)创建一个映射,例如从 'listB'。 - 使用流或循环遍历另一个列表(
listA
),对于每个项目,从创建的映射中找到相应的按id
匹配的项目。 - 如果条目按
id
匹配,则替换所有值为null
或空字符串的内容。
英文:
- Create a map from one list (grouping by
id
) for example from 'listB' - Iterate by other list (
listA
) with stream or for-loop, and for every item find byid
corresponding item from created map. - If entries match by
id
replace all values that arenull
or empty string.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论