-3

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

LDropl
  • 846
  • 3
  • 9
  • 25
  • Please post a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) and tell us what doesn't work, so we can see what you have tried and why it differs from the expected result. – JustAnotherDeveloper Aug 20 '20 at 08:55
  • Why do you want to use `Stream`s for that? A simple for-loop is good enough. – Amongalen Aug 20 '20 at 08:57
  • You can map `SomeObject` to `AnotherObject` in the stream of `ListA`. `ListB` is not necessary. –  Aug 20 '20 at 09:29
  • See [Iterate two Java-8-Streams together - Stack Overflow](https://stackoverflow.com/questions/24059837/iterate-two-java-8-streams-together/24063511#24063511) –  Aug 20 '20 at 09:48

1 Answers1

1
  1. Create a map from one list (grouping by id) for example from 'listB'
  2. Iterate by other list (listA) with stream or for-loop, and for every item find by id corresponding item from created map.
  3. If entries match by id replace all values that are null or empty string.
lczapski
  • 4,026
  • 3
  • 16
  • 32