in online_bontique_demo/cartService/src/main/java/org/apache/dubbo/shop/service/cart/CartServiceImpl.java [38:62]
public void addItem(String userId, CartItem newItem) {
// Retrieve the list of cart items for the user, create a new list if it doesn't exist
List<CartItem> cartItems = cartStore.computeIfAbsent(userId, k -> new ArrayList<>());
// Flag to check if the item was updated
boolean itemUpdated = false;
// Iterate through the list to check if the item already exists
for (CartItem item : cartItems) {
if (item.getProductId().equals(newItem.getProductId())) {
// If the item exists, update the quantity
item.setQuantity(item.getQuantity() + newItem.getQuantity());
itemUpdated = true;
break;
}
}
// If the item was not updated, add it as a new item
if (!itemUpdated) {
cartItems.add(newItem);
}
// Update the cartStore with the new list
cartStore.put(userId, cartItems);
}