I have two lists of Objects. Need to traves through both them, match them by id then update list1 values of that object from list 2 if the id matches.
I know how to do it with old java but wondering if it can be done in JAVA8 (stream)
class Person {
String id ;
String name;
String age;
}
p1:{1,test1,3}
p2:{2,test2,6}
p3:{3,test3,8}
p4:{1,test1,33}
p5:{2,test22,16}
p6:{3,test3,18}
p10:{10,test10,8}
List<Person> list1 = {p1,p2, p3, p10};
List<Person> list2 = {p4,p5, p6};
wanting the end result like this
list1 = {p1,p2, p3, p10}
p1:{1,test1,33}
p2:{2,test22,16}
p3:{3,test3,18}
p10:{10,test10,8}
basically, I want if the id matches I want the values to be overridden from list2 to list 1 (don't want list 3)
so far I was able to match them by id but then I am lost how to update the fields...
List<CartItemAttribute> test = existingCartItem.get().getAttributes().stream()
.filter(x -> (cartItem.getAttributes().stream()
.filter(y->y.getCartItemAttributeId()== x.getCartItemAttributeId())
.count()<1
)).collect(Collectors.toList());
here is what i have that works as expected
private void upsertAttributes(CartItem cartItem, Optional<CartItem> existingCartItem) {
boolean addAtribute = true;
List<CartItemAttribute> existingAttribute = existingCartItem.get().getAttributes();
for (CartItemAttribute requestingList: cartItem.getAttributes()) {
addAtribute = true;
for (CartItemAttribute existingList: existingAttribute) {
if(StringUtils.isNotBlank(requestingList.getCartItemAttributeId())
&& requestingList.getCartItemAttributeId()
.equals(existingList.getCartItemAttributeId())) {
existingList.setKey(requestingList.getKey());
existingList.setValue(requestingList.getValue());
addAtribute = false;
}
}
if(addAtribute) {
existingAttribute.add(requestingList);
}
}
}