Raju Sidda :
I have two list of objects accounts and salaries and I need to iterate the list of objects. If the id matches I need to update the account object.
I have list1 and list2 these two objects are different object type. we need to update the object(param) in list1 with list2 object(param).
Example
if(accounts !=null && salaries!=null) { // checking for nulls
for (Account obj1 : accounts) {// iterating objects
for (Salary obj2 : salaries) {
String id = ibj2.getId();
if (id.equals(obj1.getId())) {// id checks
obj1.setxxxx(obj2.getxxxx());// set the value
}
}
}
}
I tried:
list1.stream().flatMap(x -> list2 .stream() .filter(y -> x.getId().equals(y.getId())));
Sharon Ben Asher :
The final operation, obj1.setxxxx(obj2.getxxxx());
requires to have both obj1
and obj2
. that dictates the item that is streamed from both lists
list1.stream()
.forEach(obj1 ->
list2.stream()
.filter(obj2 -> obj1.getId().equals(obj2.getId()))
.findFirst()
.ifPresent(obj2 -> obj1.setxxxx(obj2.getxxxx()))
);