Instead of adding p
to the list, can't you just update p2
? That way you don't have to modify the list while iterating.
Also, your logic is a bit off, you need to have the if
inside the for
loop. Here is one way of doing it:
boolean foundIt = false;
for (Produto p2 : listItems) {
//Verify if has a product in list with the same name
if (p2.getName().equalsIgnoreCase(p.getName())) {
//increase the product quantity
p2.setQuantity((int) (p2.getQuantity() + 1));
foundIt = true;
break;
}
}
if (!foundIt) {
listItems.add(p);
}